一.题目描述
定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一格是可以走的路。
二.代码
public int[][] directions = {
{0, 1},
{1, 0},
{-1, 0},
{0, -1}
};
private Stack<int[]> path = new Stack<>();;
private ArrayList<int[]> minPath;
private int[][] matrix;
private boolean[][] visited;
public void min(int[][] matrix) {
visited = new boolean[matrix.length][matrix[0].length];
this.matrix = matrix;
dfs(0, 0);
}
private void dfs(int i, int j) {
if (i > matrix.length - 1 || i < 0 || j > matrix[0].length - 1 || j < 0 ||
visited[i][j] || matrix[i][j] == 1 ||
(minPath != null && path.size() >= minPath.size())) {
return;
}
if (i == matrix.length - 1 && j == matrix[0].length - 1) {
path.add(new int[] {i, j});
minPath = new ArrayList<>(path);
path.pop();
return;
}
path.add(new int[] {i, j});
visited[i][j] = true;
for (int[] direction : directions) {
dfs(i + direction[0], j + direction[1]);
}
visited[i][j] = false;
path.pop();
}