题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

本题是常规dfs和bfs常规应用题,要注意的是,需要输出路径的话,最好使用dfs,如果用bfs需要额外定义链表结构来辅助记录路径信息,如果要求最短路径的数量,用bfs最好
import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        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();
            }
        }

        maze[0][0] = 1;
        List<int[]> curPath = new ArrayList<>();
        curPath.add(new int[]{0, 0});
        dfs(maze, curPath, 0, 0);

        for (int[] step : minPath) {
            System.out.println("(" + step[0] + "," + step[1] + ")");
        }
    }


    static List<int[]> minPath = null;
    static int[][] steps = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    static void dfs(int[][] maze, List<int[]> curPath, int curI, int curJ) {
        if (curI == maze.length - 1 && curJ == maze[0].length - 1) {
            if (minPath == null || minPath.size() > curPath.size()) {
                minPath = new ArrayList<>(curPath);
            }
            return;
        }
        for (int[] nextStep : steps) {
            int nextI = curI + nextStep[0];
            int nextJ = curJ + nextStep[1];
            if (nextI >= 0 && nextJ >= 0
                    && nextI < maze.length && nextJ < maze[0].length
                    && maze[nextI][nextJ] != 1) {
                maze[nextI][nextJ] = 1;
                curPath.add(new int[]{nextI, nextJ});
                dfs(maze, curPath, nextI, nextJ);
                curPath.remove(curPath.size() - 1);
                maze[nextI][nextJ] = 0;
            }
        }
    }
}


全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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