迷宫问题

迷宫问题

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

import java.util.*;

public class Main 
{
    private int n;
    private int m;
    private int[][] maze;
    private class Pair {
        int i;
        int j;
        Pair(int i, int j) {
            this.i = i;
            this.j = j;
        }
        public String toString() {
            return "(" + i + "," + j + ")";
        }
    }

    public Main(int n, int m, int[][] maze) {
        this.n = n;
        this.m = m;
        this.maze = maze;
    }

    private boolean dfs(int[][] maze, int i, int j, Stack<Pair>paths) {
        if (maze[i][j] != 0) return false;
        paths.push(new Pair(i, j));
        // at the end point
        if (i == n - 1 && j == m - 1) return true;
        // go down
        if (i + 1 < n && dfs(maze, i+1, j, paths)) {
            return true;
        }
        // go right
        if (j + 1 < m && dfs(maze, i, j+1, paths)) {
            return true;
        }
        paths.pop();
        return false;
    }

    public void solve() {
        Stack<Pair> paths = new Stack<>();
        dfs(maze, 0, 0, paths);
        for (Pair point : paths) {
            System.out.println(point);
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[][] maze = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    maze[i][j] = in.nextInt();
                }
            }
            Main solution = new Main(n, m, maze);
            solution.solve();
        }
    }
}
全部评论
这个是不是不能往上走
点赞 回复 分享
发布于 2020-08-21 20:07

相关推荐

Pandaileee:校友加油我现在也只有一个保底太难了
点赞 评论 收藏
分享
想润的芹菜人狠话不多:把其中一个老总放中间都会得罪另一个
点赞 评论 收藏
分享
HNU_fsq:建议直接出国,这简历太6了。自愧不如
点赞 评论 收藏
分享
6 3 评论
分享
牛客网
牛客企业服务