题解 | 迷宫问题

迷宫问题

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

import java.util.Scanner;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

/**
 * 迷宫问题
 */
public class Main {

    private static final int[] dx = {-1, 1, 0, 0};
    private static final int[] dy = {0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int h = sc.nextInt();
            int w = sc.nextInt();

            int[][] grid = new int[h][w];
            for (int i = 0; i < h; i++) {
                for (int j = 0; j < w; j++) {
                    grid[i][j] = sc.nextInt();
                }
            }

            Queue<int[]> queue = new ArrayDeque<>();
            int[] root = {0, 0};
            queue.offer(root);

            // 记录前一个路径
            int[][][] parent = new int[h][w][2];

            boolean[][] visited = new boolean[h][w];
            visited[0][0] = true;

            while (!queue.isEmpty()) {
                int[] curr = queue.poll();
                int x = curr[0];
                int y = curr[1];

                // break条件,x,y是终点
                if (x == h - 1 && y == w - 1) break;

                // 从四个方向进行遍历
                for (int i = 0; i < 4; i++) {
                    int nx = x + dx[i];
                    int ny = y + dy[i];


                    // 坐标有效,且可以通行
                    if (nx >= 0 && nx < h && ny >= 0 && ny < w && grid[nx][ny] == 0 &&
                            !visited[nx][ny]) {
                        parent[nx][ny][0] = x;
                        parent[nx][ny][1] = y;
                        queue.offer(new int[] {nx, ny});
                        visited[nx][ny] = true;
                    }
                }
            }

            // 回溯路径
            List<String> path = new ArrayList<>();
            int cx = h - 1, cy = w - 1;
            while (cx != 0 || cy != 0) {
                // 添加目的地坐标
                path.add("(" + cx + "," + cy + ")");
                // 获取终点的前驱坐标
                int px = parent[cx][cy][0];
                int py = parent[cx][cy][1];
                // 继续向前查找,找到前一个坐标
                cx = px;
                cy = py;
            }
            // 添加终点
            path.add("(0,0)");
            Collections.reverse(path);

            // 格式化输出
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < path.size(); i++) {
                sb.append(path.get(i));
                if (i < path.size() - 1) sb.append("\n");
            }
            System.out.println(sb);
        }
        sc.close();
    }
}

全部评论

相关推荐

Rac000n:淘天-客户运营部-AI研发工程师,智能客服方向,暑期实习招聘,欢迎联系
点赞 评论 收藏
分享
03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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