01 Matrix
来源:互联网 发布:淘宝客可以关闭吗 编辑:程序博客网 时间:2024/06/07 11:23
原题链接: 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.
Solution: 考虑用动态规划的方法来求解。对于每一个cell来说,它到nearest 0 的距离应该等于min { 邻居到nearest 0 的最短距离 + 1}。因为此题求的是最短距离,所以我们的动态规划过程可以先从该矩阵中为0的cell开始,然后向其邻居转移。为此,我们使用一个队列,将每一个已被访问但还未向其邻居转移的cell加入到队列中,进而完成动态规划化的状态转移过程。
class Solution {public: vector<vector<int>> updateMatrix(vector<vector<int>>& A) { int m = A.size(), n = A[0].size(); vector<vector<int>> distance(m, vector<int>(n, 101)); bool visited[m][n]; memset(visited, false, sizeof(visited)); queue<pair<int, int>> Q; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == 0) { distance[i][j] = 0; Q.push(make_pair(i, j)); visited[i][j] = true; } } } int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; while (!Q.empty()) { int x = Q.front().first; int y = Q.front().second; Q.pop(); for (int i = 0; i < 4; ++i) { if (x + dx[i] < m && x + dx[i] >= 0 && y + dy[i] < n && y + dy[i] >= 0 && !visited[x + dx[i]][y + dy[i]]) { distance[x + dx[i]][y + dy[i]] = min(distance[x + dx[i]][y + dy[i]], distance[x][y] + 1); Q.push(make_pair(x + dx[i], y + dy[i])); visited[x + dx[i]][y + dy[i]] = true; } } } return distance; }};
算法分析: 对于一个m x n的矩阵,我们需要大约O(m x n)的时间复杂度。
阅读全文
0 0
- 01 Matrix
- 01 Matrix
- 01 Matrix
- 01 Matrix
- 01 Matrix
- 01 Matrix
- hdu 01 Matrix
- 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
- leetcode-542-01 Matrix
- leetcode542. 01 Matrix
- 542. 01 Matrix
- xRecyclerView刷新(升级上一篇)
- Rxjava2.0和Retrofit2.0结合使用(2)post请求
- 电商ERP系统——商品SKU与库存设计
- 1031. 查验身份证(15)
- 输出国际象棋棋盘
- 01 Matrix
- 原型模式
- Spring MVC之@RequestMapping 详解
- 生成随机代码
- NOIP 2017退役记
- 计算阶梯数
- 透彻理解c++模板包含模型(转)
- Javascript异步编程的4种方法
- i++,a+=5的实现原理