题解 | #迷宫问题#

迷宫问题

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;


    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务