LeetCode部分题解
来源:互联网 发布:种植药材前景 知乎 编辑:程序博客网 时间:2024/06/10 16:00
LeetCode Algorithm部分.542
【542】01 Matrix
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 0
0 1 0
0 0 0Output:
0 0 0
0 1 0
0 0 0Example 2:
Input:0 0 0
0 1 0
1 1 1Output:
0 0 0
0 1 0
1 2 1Note:
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矩阵,找到每个元素距离最近0元素的距离。
class Solution {public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int M = matrix.size(), N = matrix[0].size(); queue<pair<int, int>> q; for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { if (!matrix[i][j]) q.emplace(i, j); else matrix[i][j] = INT_MAX; } } int dirs[][2] = {{ -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }}; while (q.size()) { auto p = q.front(); q.pop(); for (auto dir : dirs) { int x = p.first + dir[0], y = p.second + dir[1]; if (x >= 0 && x < M && y >= 0 && y < N && matrix[x][y] == INT_MAX) { matrix[x][y] = matrix[p.first][p.second] + 1; q.emplace(x, y); } } } return matrix; }};
以上是复杂度为O(n^2)算法的实现
0 0
- leetcode 部分题解(python)
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- LeetCode部分题解
- Python 学习 (Leetcode 算法题解【easy部分 技巧总结】)
- leetcode题解
- leetcode题解
- LeetCode 题解
- leetCode题解
- leetcode题解
- leetcode题解
- leetcode题解
- EventBus全面讲解和案例
- centos7 防火墙问题
- 485. Max Consecutive Ones
- Ubuntu 16.10 小记
- java中奇葩异常一
- LeetCode部分题解
- zip、enumerate
- 27. Remove Element
- 有序关联容器
- 3月25日 C4(华中赛区,郑轻)参赛感想
- Tensorflow安装
- 登录界面
- JVM你必需知道的基础
- C++ Primer_4th第六章学习笔记