LeetCode 542. 01 Matrix

原题链接在这里:https://leetcode.com/problems/01-matrix/description/

题目:

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 0
0 1 0
0 0 0

Output:

0 0 0
0 1 0
0 0 0

Example 2: 
Input:

0 0 0
0 1 0
1 1 1

Output:

0 0 0
0 1 0
1 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.

题解:

先把非0点标记成Integer.MAX_VALUE. 然后从每个0点开始做BFS. 若是对周围的点更新出更小的值就把更小值放入queue中用作将来的BFS.

Time Complexity: O(m*n). m = matrix.length, n = matrix[0].length. 每个点最多进入queue 4 次.

Space: O(m*n). queue size.

AC Java:

 1 class Solution {
 2     public int[][] updateMatrix(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 4             return matrix;
 5         }
 6         
 7         int m = matrix.length;
 8         int n = matrix[0].length;
 9         
10         LinkedList<int []> que = new LinkedList<int []>();
11         for(int i = 0; i<m; i++){
12             for(int j = 0; j<n; j++){
13                 if(matrix[i][j] == 0){
14                     que.add(new int[]{i, j});
15                 }else{
16                     matrix[i][j] = Integer.MAX_VALUE;
17                 }
18             }
19         }
20         
21         int [][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
22         
23         while(!que.isEmpty()){
24             int [] cur = que.poll();
25             for(int [] dir : dirs){
26                 int dx = cur[0] + dir[0];
27                 int dy = cur[1] + dir[1];
28                 if(dx<0 || dx>=m || dy<0 || dy>=n || matrix[cur[0]][cur[1]]+1>=matrix[dx][dy]){
29                     continue;
30                 }
31                 
32                 matrix[dx][dy] = matrix[cur[0]][cur[1]]+1;
33                 que.add(new int[]{dx, dy});
34             }
35         }
36         
37         return matrix;
38     }
39 }

类似Shortest Path to Get Food.

posted @ 2018-09-07 07:17  Dylan_Java_NYC  阅读(460)  评论(0编辑  收藏  举报