1. 题目描述:
定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一空格是可以走的路。
Input
一个N × M的二维数组,表示一个迷宫。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
2. 代码
BFS广度优先遍历
public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int rows = sc.nextInt(); int cols = sc.nextInt(); int[][] maze = new int[rows][cols]; for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++) maze[i][j] = sc.nextInt(); } printTrace(maze); } } public static void printTrace(int[][] maze){ int rows = maze.length; int cols = maze[0].length; node start = new node(0, 0); boolean[][] visited = new boolean[rows][cols]; LinkedList<node> stack = new LinkedList<>(); //用一个栈来保存已经访问过的点 stack.push(start); int[] dx = new int[]{1,0}; int[] dy = new int[]{0,1}; while(!stack.isEmpty()){ boolean flag = false; node peek = stack.peek(); if(peek.x == rows - 1 && peek.y == cols - 1){ break; } else{ for(int i = 0; i < 2; i++){ node newNode = new node(peek.x + dx[i], peek.y + dy[i]); if(newNode.x < rows && newNode.y < cols && maze[newNode.x][newNode.y] == 0 && !visited[newNode.x][newNode.y]){ stack.push(newNode); //如果满足0且未被访问则入队 visited[newNode.x][newNode.y] = true; //标记已访问 flag = true; break; } } if(!flag){ stack.pop(); } //说明两条路都走不通 } } LinkedList<node> temp = new LinkedList<>(); while(!stack.isEmpty()) temp.push(stack.pop()); while(!temp.isEmpty()){ System.out.println("(" + temp.peek().x + "," + temp.peek().y + ")"); temp.pop(); } } } class node{ int x; int y; public node(int x, int y){ this.x = x; this.y = y; } }