文章目录
题目描述解题思路代码如下相似题目
题目描述
定义一个二维数组N*M(其中2
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int row = sc.nextInt();
int col = sc.nextInt();
//矩阵
int[][] mat = new int[row][col];
for (int i = 0; i
mat[i][j] = sc.nextInt();
}
}
//搜索最短路径
ArrayList path = new ArrayList();
ArrayList minPath = new ArrayList();
int[][] book = new int[row][col];
getMinPath(mat,row,col,0,0,book,path,minPath);
//打印
for (Node n:minPath
) {
System.out.println("("+n.x+","+n.y+")");
}
}
}
/**
* 迷宫问题
* @param mat 迷宫矩阵
* @param row 迷宫矩阵的行
* @param col 迷宫矩阵的列
* @param x 当前位置横坐标
* @param y 当前位置纵坐标
* @param book 标记矩阵,当前位置是否走过
* @param path 保存当前路径的每个位置
* @param minPath 保存最短路径
*/
public static void getMinPath(int[][] mat, int row, int col, int x, int y, int[][] book, ArrayList path, ArrayList minPath) {
//判断x,y是否越界,是否走过,是否为1
if(x=row||y=col||book[x][y]==1||mat[x][y]==1){
return;
}
//把当前位置存入路径中
path.add(new Node(x,y));
//走过了,标记当前位置
book[x][y] = 1;
//判断当前位置是否为出口位置
if(x == row-1&&y==col-1){
//一条新的路径产生
//判断是否为更短路径
if (minPath.isEmpty() || path.size()
minPath.add(n);
}
}
}
//继续搜索(x,y)的上下左右四个方向
getMinPath(mat, row, col, x+1, y, book, path, minPath);
getMinPath(mat, row, col, x-1, y, book, path, minPath);
getMinPath(mat, row, col, x, y+1, book, path, minPath);
getMinPath(mat, row, col, x, y-1, book, path, minPath);
//走到这,这说明走不通了
//把当前位置删除,寻找新的路径
path.remove(path.size()-1);
book[x][y]=0;
}
}
相似题目
走方格的方案数
|