1. 程式人生 > 實用技巧 >遞迴尋找二維陣列的最短(長)路勁長度

遞迴尋找二維陣列的最短(長)路勁長度


 有一個二維陣列,每個位置上有一個數字,表示經過這個點需要消耗的體力值,
現在需要從左上角 (00) 位置走到右下角(9,9) 位置,請找出一條路,使得消耗的體力值最小


public class findWay {

public static void main(String[] args) {

int[][] map = new int[10][10];
int row = map.length;
int col = map[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
map[i][j] = 1;
}
}
for(int i=0;i<row;i++){
map[i][0] = 0;
map[i][3] = 0;
map[i][5] = 0;
map[i][9] = 0;
map[i][7] = 0;
}
map[9][1] = 0;
map[0][3] = 0;
map[0][8] = 0;
map[0][4] = 0;
map[9][2] = 0;
map[9][6] = 0;
print(map);

int sum = finfWay(map);
System.out.println("最短的路勁長度為: "+ sum );
}

public static int finfWay(int[][] map){
int row = map.length;
int col = map[0].length;
// 來一個深拷貝
int[][] res = new int[row][col];
for(int i =0;i<row;i++){
for(int j=0;j<col;j++){
res[i][j] = map[i][j];
}
}
boolean[][] tag = new boolean[row][col];
tag[0][0] = true;
fn(map,res,tag,0,0);
print(res);
return res[row-1][col-1];
}

private static void fn(int[][] map,int[][] res,boolean[][] tag,int i,int j){
int row = map.length;
int col = map[0].length;
if(i-1>=0){
if(!tag[i-1][j]){ //如果沒有訪問過
res[i-1][j] = res[i][j]+map[i-1][j];
tag[i-1][j] = true;
fn(map,res,tag,i-1,j);
}else{ // 訪問過
if(res[i][j]+map[i-1][j] < res[i-1][j]){
res[i-1][j] = res[i][j]+map[i-1][j];
fn(map,res,tag,i-1,j);
}
}
}
if(i+1<row){
if(!tag[i+1][j]){ //如果沒有訪問過
res[i+1][j] = res[i][j]+map[i+1][j];
tag[i+1][j] = true;
fn(map,res,tag,i+1,j);
}else{ // 訪問過
if(res[i][j]+map[i+1][j] < res[i+1][j]){
res[i+1][j] = res[i][j]+map[i+1][j];
fn(map,res,tag,i+1,j);
}
}
}
if(j-1>=0){
if(!tag[i][j-1]){ //如果沒有訪問過
res[i][j-1] = res[i][j]+map[i][j-1];
tag[i][j-1] = true;
fn(map,res,tag,i-1,j);
}else{ // 訪問過
if(res[i][j]+map[i][j-1] < res[i][j-1]){
res[i][j-1] = res[i][j]+map[i][j-1];
fn(map,res,tag,i,j-1);
}
}
}
if(j+1<col){
if(!tag[i][j+1]){ //如果沒有訪問過
res[i][j+1] = res[i][j]+map[i][j+1];
tag[i][j+1] = true;
fn(map,res,tag,i,j+1);
}else{ // 訪問過
if(res[i][j]+map[i][j+1] < res[i][j+1]){
res[i][j+1] = res[i][j]+map[i][j+1];
fn(map,res,tag,i,j+1);
}
}
}
}


/** 列印結果展示 */
public static void print(int[][] map ){
int row = map.length;
int col = map[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(col>9){
System.out.print(map[i][j]+" ");
}else{
System.out.print(" "+map[i][j]+" ");
}
}
System.out.println();
}
System.out.println();
}
}