描述
定义一个二维数组 N*M ,如 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],既第一格是可以走的路。
数据范围: 2≤n,m≤10 , 输入的内容只包含 0≤val≤1
输入描述:
输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
输出描述:
左上角到右下角的最短路径,格式如样例所示。
示例1
输入:
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
输出:
(0,0) (1,0) (2,0) (2,1) (2,2) (2,3) (2,4) (3,4) (4,4)
示例2
输入:
5 5 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 1 0 0 0 0 0 0
输出:
(0,0) (1,0) (2,0) (3,0) (4,0) (4,1) (4,2) (4,3) (4,4)
说明:
注意:不能斜着走!!
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] maze = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
maze[i][j] = scanner.nextInt();
}
}
List<String> path = findPath(maze);
for (String p : path) {
System.out.println(p);
}
}
public static List<String> findPath(int[][] maze) {
List<String> path = new ArrayList<>();
int n = maze.length;
int m = maze[0].length;
int[][] directions = {{0, 1}, {1, 0}};
boolean[][] visited = new boolean[n][m];
dfs(maze, visited, directions, path, 0, 0, n, m);
return path;
}
public static boolean dfs(int[][] maze, boolean[][] visited, int[][] directions, List<String> path, int x, int y, int n, int m) {
if (x == n - 1 && y == m - 1) {
path.add("(" + x + "," + y + ")");
return true;
}
visited[x][y] = true;
for (int[] direction : directions) {
int newX = x + direction[0];
int newY = y + direction[1];
if (newX >= 0 && newX < n && newY >= 0 && newY < m && maze[newX][newY] == 0 && !visited[newX][newY]) {
if (dfs(maze, visited, directions, path, newX, newY, n, m)) {
path.add("(" + x + "," + y + ")");
return true;
}
}
}
return false;
}
}
这个程序首先从输入中读取迷宫的大小和内容,然后调用 findPath
函数来查找从左上角到右下角的最短路径。findPath
函数使用深度优先搜索算法来遍历迷宫,并将找到的路径添加到 path
列表中。最后,程序将路径打印到控制台。
注意,这个程序使用了 Scanner
类来读取输入,并使用了 List
类来存储路径。在 dfs
函数中,我们使用了一个 visited
数组来记录已经访问过的位置,以避免重复访问。我们还使用了一个 directions
数组来表示可以移动的方向,这里只有两个方向:向右和向下。