zoukankan      html  css  js  c++  java
  • Leetcode 542.01矩阵

    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 }
  • 相关阅读:
    HOG特征提取+python+opencv
    统计模型计算量~pytorch
    CycleGAN训练~训练图像进行拼接
    缺陷检测~分类网络
    缺陷检测~分类网络
    缺陷检测~检测网络
    pytorch中的fc和fc逆操作
    pytorch中的view和view逆操作
    传统的图像特征提取
    TensorFlow安装+入门操作
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10373953.html
Copyright © 2011-2022 走看看