题解 | #迷宫问题#

迷宫问题

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

import java.util.*;
public class Main {
    public static class pos {
        int x;
        int y;
        pos(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    static int[][]map;
    static List<pos> ans=new ArrayList<>();
    static List<pos> res=new ArrayList<>();
    static int m, n;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m1 = sc.nextInt();
        int n1 = sc.nextInt();
        m = m1;
        n = n1;
        map = new int[m][n];
        for (int i = 0; i < m1; i++) {
            for (int j = 0; j < n1; j++) {
                map[i][j] = sc.nextInt();
            }
        }
        
        dfs(0,0);
        for(pos p:res){
            System.out.println("("+p.x+","+p.y+")");
        }


    }

    static void dfs(int x, int y) {
        ans.add(new pos(x, y));
        map[x][y] = 1;
        if(x==m-1&&y==n-1){res=new ArrayList<>(ans);return;}

        if (x + 1 <  m && map[x + 1][y] == 0) dfs(x + 1, y);
        if (x - 1 >= 0 && map[x - 1][y] == 0) dfs(x - 1, y);
        if (y + 1 < n && map[x][y + 1] == 0)  dfs(x, y + 1);
        if (y - 1 >= 0 && map[x][y - 1] == 0) dfs(x, y - 1);

        ans.remove(ans.size() - 1);
        map[x][y] = 0;


    }
}
全部评论

相关推荐

06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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