首页 > 其他 > 详细

Leetcode 542.01矩阵

时间:2019-02-14 13:39:29      阅读:167      评论:0      收藏:0      [点我收藏+]

01矩阵

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1:
输入:

0 0 0

0 1 0

0 0 0

输出:

0 0 0

0 1 0

0 0 0

示例 2:
输入:

0 0 0

0 1 0

1 1 1

输出:

0 0 0

0 1 0

1 2 1

注意:

  1. 给定矩阵的元素个数不超过 10000。
  2. 给定矩阵中至少有一个元素是 0。
  3. 矩阵中的元素只在四个方向上相邻: 上、下、左、右。

 

思路

先把所有0入队,把1置为MAX_VALUE,然后把最靠近0的1的距离算出来,然后将他们入队,再算距离最靠近0的1的1的距离算出来,依次处理

 

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

 

Leetcode 542.01矩阵

原文:https://www.cnblogs.com/kexinxin/p/10373953.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!