地牢逃脱, 网易笔试题

宽度优先遍历,可访问位置.记录到出发点的最近距离。

深度优先遍历不好做。

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        char[][] grid = new char[n][m];
        boolean[][] used = new boolean[n][m];
        for(int i=0; i < n; i++) {
            char[] chars = sc.next().toCharArray();
            grid[i] = chars;
            for(int j=0; j < m; j++) if(chars[j] == 'X') used[i][j] = true;
        }
        int sx = sc.nextInt(), sy = sc.nextInt();
        int k = sc.nextInt();
        int[][] dir = new int[k][2];
        for(int i=0; i < k; i++) {
            dir[i][0] = sc.nextInt();
            dir[i][1] = sc.nextInt();
        }
        int[][] res = new int[n][m];
        for(int i=0; i < n; i++) Arrays.fill(res[i], m*n);
        int step = 0; 
        Queue<Integer> q = new LinkedList<>();
        q.offer(sx*m+sy); res[sx][sy] = 0;
        while(!q.isEmpty()) {
            int size = q.size();
            step++;
            for(int i=0; i < size; i++) {
                int cur = q.poll();
                int x = cur/m, y = cur%m;
                for(int j=0; j < k; j++) {
                    int xx = x + dir[j][0], yy = y + dir[j][1];
                    if(xx >= 0 && xx < n && yy >= 0 && yy < m && !used[xx][yy]) {
                        q.offer(xx*m+yy);
                        used[xx][yy] = true;
                        res[xx][yy] = step;
                    }
                }
            }
        }
        int ans = 0;
        for(int i=0; i < n; i++) 
            for(int j=0; j < m; j++) 
                if(grid[i][j] == '.')
                    ans = Math.max(ans, res[i][j]);
        if(ans == n*m)
            System.out.println(-1);
        else
            System.out.println(ans);
    }
}
原文地址:https://www.cnblogs.com/lixyuan/p/13148723.html