542. 01 Matrix
来源:互联网 发布:opencv python视频教程 编辑:程序博客网 时间:2024/05/29 19:07
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 0Output:
0 0 00 1 00 0 0
Example 2:
Input:
0 0 00 1 01 1 1Output:
0 0 00 1 01 2 1
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.
本题给出一个01矩阵,要求求出矩阵中的1到最近的0的距离
一开始我用动态规划的思想递归求解min( min( dis(le), dis(ri)), min( dis(up), dis(dn) ) ) +1,但是发现在递归过程中,发现在求dis(le)的时候会用到原来的点的距离,导致程序出错。后来想到找出矩阵中值为0的点,从这些点开始用BFS方式把距离“扩散”出去,不为0的点则从周围4点取最小值加1。由于之前扩散过的点在发现新的值为0的点后可能会有更小的距离,所以我们使用两次扩散,一次从矩阵左上角开始,一次从右下角。详细代码如下:
class Solution {public: #define IMAX INT_MAX vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { vector<int> temp; vector<vector<int> > res; if(matrix.size() == 0) return res; for(int i = 0; i < matrix[0].size(); i++) temp.push_back(IMAX); for(int i = 0; i < matrix.size(); i++) res.push_back(temp); for(int i = 0; i < matrix.size(); i++) { for(int j = 0; j < matrix[i].size(); j++) { if(matrix[i][j] == 0) res[i][j] = 0; else { if(i && res[i-1][j] != IMAX && res[i-1][j] < res[i][j]) res[i][j] = res[i-1][j] + 1; if(j && res[i][j-1] != IMAX && res[i][j-1] < res[i][j]) res[i][j] = res[i][j-1] + 1; if(i < matrix.size() - 1 && res[i+1][j] != IMAX && res[i+1][j] < res[i][j]) res[i][j] = res[i+1][j] + 1; if(j < matrix[i].size() - 1 && res[i][j+1] != IMAX && res[i][j+1] < res[i][j]) res[i][j] = res[i][j+1] + 1; } } } for(int i = matrix.size() - 1; i >= 0; i--) { for(int j = matrix[i].size() - 1; j >= 0; j--) { if(matrix[i][j] == 0) res[i][j] = 0; else { if(i && res[i-1][j] != IMAX && res[i-1][j] < res[i][j]) res[i][j] = res[i-1][j] + 1; if(j && res[i][j-1] != IMAX && res[i][j-1] < res[i][j]) res[i][j] = res[i][j-1] + 1; if(i < matrix.size() - 1 && res[i+1][j] != IMAX && res[i+1][j] < res[i][j]) res[i][j] = res[i+1][j] + 1; if(j < matrix[i].size() - 1 && res[i][j+1] != IMAX && res[i][j+1] < res[i][j]) res[i][j] = res[i][j+1] + 1; } } } return res; }};
阅读全文
0 0
- 542. 01 Matrix
- Leetcode-542. 01 Matrix
- 542. 01 Matrix
- [LeetCode]542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- leetcode 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix 题解
- [leetcode]542. 01 Matrix
- 【LeetCode】542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix [LeetCode]
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- spring事务回滚问题
- 大脑双核单总线模型~《程序员思维的修炼》读后感
- Kotlin-10.接口(interface)
- 最小生成树的两种最基本的算法
- 欢迎使用CSDN-markdown编辑器
- 542. 01 Matrix
- head first 设计模式 Observer模式
- filter、map、reduce学习
- Oracle第二、三章 限制数据查询
- poj 1218 THE DRUNK JAILER
- C数据结构设计中,表首结点和二叉树根结点的头指针——传指针还是传指针的指针?
- BZOJ4241 历史研究 (分块 回滚莫队-教程向)
- java继承
- C++11 std::unique_lock与std::lock_guard区别及多线程应用实例