题解 | #迷宫问题#

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;
        }
    }

}


全部评论

相关推荐

06-11 15:52
东南大学 C++
问了一下hr,这个回答是G了吗
椛鸣:我遇到过 我给你翻一下 对不起 我之前把你当备胎了 现在我人已经招满了 ***吧
点赞 评论 收藏
分享
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务