题解 | #迷宫问题#
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
1.广度优先搜索,第一个到达终点的路径即为最短路径。
2.使用队列代替递归
import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; 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[][] nums = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { nums[i][j] = sc.nextInt (); } } boolean[][] flags = new boolean[row][col]; ArrayList <Point> arr = new ArrayList <> (); LinkedList <Point> queue = new LinkedList <> (); Point root = new Point ( 0, 0, null ); queue.offer ( root ); while (!queue.isEmpty ()) { Point current = queue.poll (); int c1 = current.m; int c2 = current.n; arr.add ( current ); if (c1 == row - 1 && c2 == col - 1) { break; } //四个方向 if (c1 - 1 >= 0 && nums[c1 - 1][c2] == 0 && !flags[c1 - 1][c2]) { queue.offer ( new Point ( c1 - 1, c2, current ) ); } if (c1 + 1 < row && nums[c1 + 1][c2] == 0 && !flags[c1 + 1][c2]) { queue.offer ( new Point ( c1 + 1, c2, current ) ); } if (c2 - 1 >= 0 && nums[c1][c2 - 1] == 0 && !flags[c1][c2 - 1]) { queue.offer ( new Point ( c1, c2 - 1, current ) ); } if (c2 + 1 < col && nums[c1][c2 + 1] == 0 && !flags[c1][c2 + 1]) { queue.offer ( new Point ( c1, c2 + 1, current ) ); } flags[c1][c2] = true; } Point p = arr.get ( arr.size () - 1 ); LinkedList <Point> stack = new LinkedList <> (); while (p != null) { stack.push ( p ); p = p.father; } while (!stack.isEmpty ()) { Point po = stack.pop (); System.out.println ( "(" + po.m + "," + po.n + ")" ); } } } private static class Point { int m; int n; Point father; public Point(int m, int n, Point father) { this.m = m; this.n = n; this.father = father; } } }