题解 | 迷宫寻路

迷宫寻路

https://www.nowcoder.com/practice/0c8930e517444d04b426e9703d483ed4

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static int n, m;
    public static String ans = "No";
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        String sa = in.nextLine();
        String[] strs = new String[n];
        int index = 0;
        char[][] chars = new char[n][m];
        
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            strs[index] = in.nextLine();
            chars[index] = strs[index].toCharArray();
            index++;
        }
        dfs(chars);
        System.out.println(ans);
    }

    public static void dfs(char[][] graph){
        if(graph == null || graph.length == 0){
            return;
        }

        helper(0,0,graph);
    }

    public static void helper(int r, int c, char[][ ] graph){
        if(r < 0 || c < 0 || r >= n || c >= m){
            return;
        }
        // 如果不是空地,直接返回
        if(graph[r][c] != '.'){
            return;
        }
        // 检查是否到达终点
        if(r == n - 1 && c == m - 1){
            ans = "Yes";
            return;
        }
        // 标记当前位置为已访问
        graph[r][c] = '#';
        
        // 向四个方向递归搜索
        helper(r - 1, c, graph);
        helper(r + 1, c, graph);
        helper(r, c - 1, graph);
        helper(r, c + 1, graph);
    }
}

全部评论

相关推荐

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

创作者周榜

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