542. 01 Matrix

来源:互联网 发布:航仕科技 知乎 编辑:程序博客网 时间:2024/05/22 12:40

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 00 1 00 0 0
Output:
0 0 00 1 00 0 0

Example 2: 
Input:

0 0 00 1 01 1 1
Output:
0 0 00 1 01 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

这道题要熟悉坐标型bfs的坐标表示,和越界情况的判断。同时这道题如果按以前的方法,一个点压如queue,然后bfs的话,会超时。对这道题进行分析

可以将所有为0的点都存入queue,同时将matrix里所有为1的点的值重设置为一个很大的数。对这些都为0的点进行bfs


class Solution {    public int[][] updateMatrix(int[][] matrix) {       int m = matrix.length;        int n = matrix[0].length;                Queue<int[]> queue = new LinkedList<>();        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (matrix[i][j] == 0) {                    queue.offer(new int[] {i, j});                }                else {                    matrix[i][j] = Integer.MAX_VALUE;                }            }        }                int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};                while (!queue.isEmpty()) {            int[] cell = queue.poll();            for (int[] d : dirs) {                int r = cell[0] + d[0];                int c = cell[1] + d[1];                if (r < 0 || r >= m || c < 0 || c >= n ||                     matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue;                queue.add(new int[] {r, c});                matrix[r][c] = matrix[cell[0]][cell[1]] + 1;            }        }                return matrix;     }}

原创粉丝点击