题解 | #迷宫问题#

迷宫问题

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

递归

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    private static int n;
    private static int m;
    private static int[][] maze;

    private static class Point {
        int x;
        int y;

        Point(int x,int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "(" + x + "," + y + ")";
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            n = sc.nextInt();
            m = sc.nextInt();
            maze = new int[n][m];
            for (int i = 0;i < n;i++) {
                for (int j = 0;j < m;j++) {
                    maze[i][j] = sc.nextInt();
                }
            }
            find(0,0,new ArrayList<>());
        }
    }

    private static void find(int x,int y,List<Point> list) {
        // 越界
        if (x < 0 || y < 0 || x > n-1 || y > m-1) {
            return;
        }

        // 终点
        if (x == n-1 && y == m-1) {
            List<Point> newList = new ArrayList<>(list);
            newList.add(new Point(x,y));
            for (Point point : newList) {
                System.out.println(point);
            }
            return;
        }

        // 否则是0才继续往下走
        if (maze[x][y] == 0) {
            List<Point> newList = new ArrayList<>(list);
            newList.add(new Point(x,y));
            // 走过的点不能再走,防止无限递归
            maze[x][y] = 1;
            // 上下左右四个方向,不用判断往回走
            find(x + 1,y,newList);
            find(x - 1,y,newList);
            find(x,y + 1,newList);
            find(x,y - 1,newList);
        }
        return;
    }
}
全部评论
稍微改了一下
点赞 回复 分享
发布于 2024-01-14 17:23 江西
有点像岛屿问题
点赞 回复 分享
发布于 2022-12-15 14:20 四川
秒啊
点赞 回复 分享
发布于 2022-05-30 13:40

相关推荐

点赞 评论 收藏
分享
彧未sr:查看图片
投递牧原集团等公司7个岗位
点赞 评论 收藏
分享
评论
6
1
分享

创作者周榜

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