Leetcode 542:01 矩阵 01
Leetcode 542:01 矩阵 01 Matrix### 题目:
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
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.
示例 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
注意:
- 给定矩阵的元素个数不超过 10000。
- 给定矩阵中至少有一个元素是 0。
- 矩阵中的元素只在四个方向上相邻: 上、下、左、右。
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
解题思路:
关键字:最近、距离。那肯定是广度优先搜索。类似之前的文章 岛屿数量: https://mp.weixin.qq.com/s/BrlMzXTtZWdB7hRfCKNMoQ
将这个问题转化成图,那就是求每个节点 1 到节点 0 最短的路径是多少。从某个节点开始,上下左右向外扩展,每次扩展一圈距离累加1,如:
输入:
1 1 1
0 1 0
0 0 0
转化成图(Graph),每种颜色代表一个层级:
这就变成了求某个节点到某个节点的深度了。
所以这道题有两种思路:
- 以节点1为根节点,求该节点到节点0之间的深度
- 以节点0为根节点,遇到最近的节点1路径计为1,再次以记录为1的节点为根节点继续向内遍历,遇到原节点1再次累加1并得到路径2,以此类推。。。
两种方法各有优劣,
以0节点为根节点解题,要么开辟一个新的二维数组以记录路径,要么先遍历一遍将所有的节点1的值改为不可能和路径大小重复的值。
以1节点为根节点,那么就要做一些多余的重复遍历。
以0为根节点:
逻辑顺序:
以输入下列二维数组为例:
1 1 1
0 1 1
0 0 1
先把原节点值为1 的节点改为M (路径值不可能达到的值,该题中大于10000即可)
先侵染0节点附近的M节点,0节点加1之后得到1节点
再侵染1节点附近的M节点,1节点加1之后得到2节点
......
Java:
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int row = matrix.length, column = matrix[0].length;
int[][] neighbors = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};//邻居节点的索引偏移量
Queue<int[]> queue = new LinkedList<>();//队列
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (matrix[i][j] == 0) queue.offer(new int[]{i, j});
else matrix[i][j] = Integer.MAX_VALUE;//节点值为1的节点改为一个路径不可能达到的值
}
}
while (!queue.isEmpty()) {
int[] tmp = queue.poll();
for (int i = 0; i < 4; i++) {
//得到邻居节点索引
int x = tmp[0] + neighbors[i][0];
int y = tmp[1] + neighbors[i][1];
if (x >= 0 && x < row && y >= 0 && y < column && matrix[tmp[0]][tmp[1]] < matrix[x][y]) {
matrix[x][y] = matrix[tmp[0]][tmp[1]] + 1;//该节点的值得到邻居节点的路径值+1
queue.offer(new int[]{x, y});
}
}
}
return matrix;
}
}
Python3:
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
row, column = len(matrix), len(matrix[0])
nerghbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = collections.deque()
for i in range(row):
for j in range(column):
if matrix[i][j] == 0:
queue.append((i, j))
else:
matrix[i][j] = 10001
while queue:
x, y = queue.popleft()
for i, j in nerghbors:
xx = i + x
yy = j + y
if 0 <= xx < row and 0 <= yy < column and matrix[x][y] < matrix[xx][yy]:
matrix[xx][yy] = matrix[x][y] + 1
queue.append((xx, yy))
return matrix
以1为根节点:
Java:
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int row = matrix.length, column = matrix[0].length;
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
if (matrix[i][j] == 1) matrix[i][j] = bfs(matrix, i, j, row, column);
return matrix;
}
private int bfs(int[][] matrix, int i, int j, int row, int column) {
int count = 0;
Queue<Integer> queue = new LinkedList<>();
Set<int[]> set = new HashSet<>();
queue.add(i * column + j);//记录索引的另一种方法
while (!queue.isEmpty()) {
int size = queue.size();
count += 1;
for (int k = 0; k < size; k++) {
int tmp = queue.poll();
int x = tmp / column, y = tmp % column;//得到索引坐标
//处理上下左右四个邻居节点,遇到0节点直接返回count路径值
if (x + 1 < row && !set.contains((x + 1) * column + y)) {
if (matrix[x + 1][y] != 0) queue.add((x + 1) * column + y);
else return count;
}
if (x - 1 >= 0 && !set.contains((x - 1) * column + y)) {
if (matrix[x - 1][y] != 0) queue.add((x - 1) * column + y);
else return count;
}
if (y + 1 < column && !set.contains(x * column + y + 1)) {
if (matrix[x][y + 1] != 0) queue.add(x * column + y + 1);
else return count;
}
if (y - 1 >= 0 && !set.contains(x * column + y - 1)) {
if (matrix[x][y - 1] != 0) queue.add(x * column + y - 1);
else return count;
}
}
}
return count;
}
}
Python3:
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
row, column = len(matrix), len(matrix[0])
for i in range(row):
for j in range(column):
if matrix[i][j] == 1:
matrix[i][j] = self.bfs(i, j, matrix, row, column)
return matrix
def bfs(self, i: int, j: int, matrix: List[List[int]], row: int, column: int) -> int:
queue = collections.deque()
count = 0
nodeset = set()
queue.append((i, j))
while queue:
size = len(queue)
count += 1
for i in range(size):
x, y = queue.popleft()
if x + 1 < row and (x + 1, y) not in nodeset:
if matrix[x + 1][y] != 0:
queue.append((x + 1, y))
else:
return count
if x - 1 >= 0 and (x - 1, y) not in nodeset:
if matrix[x - 1][y] != 0:
queue.append((x - 1, y))
else:
return count
if y + 1 < column and (x, y + 1) not in nodeset:
if matrix[x][y + 1] != 0:
queue.append((x, y + 1))
else:
return count
if y - 1 >= 0 and (x, y - 1) not in nodeset:
if matrix[x][y - 1] != 0:
queue.append((x, y - 1))
else:
return count
return count
欢迎关注微.信公.众号:爱写Bug
Leetcode 542:01 矩阵 01的更多相关文章
- [Swift]LeetCode542. 01 矩阵 | 01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance b ...
- Java实现 LeetCode 542 01 矩阵(暴力大法,正反便利)
542. 01 矩阵 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离. 两个相邻元素间的距离为 1 . 示例 1: 输入: 0 0 0 0 1 0 0 0 0 输出: 0 0 0 ...
- Leetcode 542.01矩阵
01矩阵 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离. 两个相邻元素间的距离为 1 . 示例 1: 输入: 0 0 0 0 1 0 0 0 0 输出: 0 0 0 0 1 0 ...
- [EOJ Monthly 2018.10][C. 痛苦的 01 矩阵]
题目链接:C. 痛苦的 01 矩阵 题目大意:原题说的很清楚了,不需要简化_(:з」∠)_ 题解:设\(r_i\)为第\(i\)行中0的个数,\(c_j\)为第\(j\)列中0的个数,\(f_{i,j ...
- LeetCode初级算法--数组01:只出现一次的数字
LeetCode初级算法--数组01:只出现一次的数字 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn. ...
- LeetCode初级算法--字符串01:反转字符串
LeetCode初级算法--字符串01:反转字符串 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.ne ...
- LeetCode初级算法--链表01:反转链表
LeetCode初级算法--链表01:反转链表 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/ ...
- LeetCode初级算法--树01:二叉树的最大深度
LeetCode初级算法--树01:二叉树的最大深度 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.n ...
- LeetCode初级算法--动态规划01:爬楼梯
LeetCode初级算法--动态规划01:爬楼梯 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net ...
随机推荐
- H5纯前端生成Excel表格
H5纯前端生成Excel表格方法如下: <!DOCTYPE html> <html> <head> <title></title> < ...
- Xml之Schema XSD约束{详细}
问题: 学习Schema其他标签的定义 约束 引入的方式: 基本格式: 1构建schema: 1.1 最基本的单位元素 1.2 元素属性 1.3 simpleType 定义类型 1.4 复合结构类型 ...
- Linux常用命令之文件编辑命令vim
vi命令 vi命令是UNIX操作系统和类UNIX操作系统中最通用的全屏幕纯文本编辑器.Linux中的vi编辑器叫vim,它是vi的增强版(vi Improved),与vi编辑器完全兼容,而且实现了很多 ...
- [01]从零开始学 ASP.NET Core 与 EntityFramework Core 课程介绍
从零开始学 ASP.NET Core 与 EntityFramework Core 课程介绍 本文作者:梁桐铭- 微软最有价值专家(Microsoft MVP) 文章会随着版本进行更新,关注我获取最新 ...
- SQL Server内部如何管理对象的数据Page?
一个表或Index使用的数据页空间是由IAM Page Chain来管理的.SQL Server 使用一个IAM(Index Allocation Map)Page来管理数据库文件中最多4GB的空间, ...
- java基础(32):类加载、反射
1. 类加载器 1.1 类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化. 加载 就是指将class文件读入内存,并为之创建一个C ...
- js键盘事件以及键盘事件拦截
一.键盘事件 onkeydown: 按下键盘时触发 onkeypress: 按下有值的键时触发 注意: onkeypress按下 Ctrl.Alt.Shift.Meta 这样无值的键,这个事件不会触发 ...
- Java之IO模型
首先来看一下同步与异步的概念: 1.同步是指当前端发起一次操作请求时,只有后台执行完所有的代码操作才会给前端返回值. 2.异步是将前端发回的消息加入消息队列,并且立刻给前端返回请求,告诉用户可以离开当 ...
- media适配css
/*引入适配的less*/ html { font-size: 16px; } @media only screen and (min-width: 320px) { html { font-size ...
- 采坑 - LODOP,打印预览
结合 layui.弹出框内容样式如下: 红框表示,左右的内边距. 图一 打印预览的样式如下:红框表示,左右的内边距. 图二 要根据图二的左右内边距,去修改图一的左右内边距.不然会影响正文内容高度的判断 ...