有一个二维数组,每个位置上有一个数字,表示经过这个点需要消耗的体力值,
现在需要从左上角 (0,0) 位置走到右下角(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();
}
}