题解 | #迷宫问题#

迷宫问题

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

import java.util.*;

// 如有一味绝境,非历十方生死
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            m = in.nextInt();
            n = in.nextInt();
            int[][] gird = new int[m][n];
            for(int y = 0; y < m; y++) {
                for(int x = 0; x < n; x++) {
                    gird[y][x] = in.nextInt();
                }
            }
            f(gird);
            for(int[] p : list) {
                 System.out.println("("+p[0] + "," + p[1] + ")");
            }
        }
    }

    public static List<int[]> f(int[][] gird) {
        list.clear();
        boolean[][] vis = new boolean[m][n];
        step(gird, vis, 0, 0, new ArrayList<int[]>());
        return list;
    }

    public static void step(int[][] gird, boolean[][] vis, int y, int x, List<int[]> cur) {
        if(y < 0 || y >= m || x < 0 || x >= n || vis[y][x] || gird[y][x] == 1) {
            return;
        }
        if(y == m-1 && x == n-1) {
            cur.add(new int[]{y, x});
            if(list.size() == 0 || cur.size() < list.size()) {
                list = new ArrayList<int[]>(cur);
            }
            cur.remove(cur.size()-1);
            return;
        }
        vis[y][x] = true;
        cur.add(new int[]{y,x});
        for(int i = 0; i < 4; i++) {
            int ny = y + dir[i][0], nx = x + dir[i][1];
            step(gird, vis, ny, nx, cur);
        }
        vis[y][x] = false;
        cur.remove(cur.size()-1);
    }

    static int m, n;
    static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}};
    static List<int[]> list = new ArrayList<>();
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务