【重点】【BFS】542.01矩阵

题目

法1:经典BFS

【重点】【BFS】542.01矩阵_第1张图片
下图中就展示了我们方法:
【重点】【BFS】542.01矩阵_第2张图片

class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[][] dist = new int[m][n];
        boolean[][] used = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                    used[i][j] = true;
                }
            }
        }
        int[] xMove = new int[]{-1, 1, 0, 0};
        int[] yMove = new int[]{0, 0, -1, 1};
        while (!queue.isEmpty()) {
            int[] curLoc = queue.poll();
            int curX = curLoc[0], curY = curLoc[1];
            for (int i = 0; i < 4; ++i) {
                int xNew = curX + xMove[i];
                int yNew = curY + yMove[i];
                if (xNew >= 0 && xNew < m && yNew >= 0 && yNew < n && !used[xNew][yNew]) {
                    queue.offer(new int[]{xNew, yNew});
                    dist[xNew][yNew] = dist[curX][curY] + 1;
                    used[xNew][yNew] = true;
                }
            }
        }

        return dist;
    }
}

你可能感兴趣的:(BFS)