【算法分析与设计】【第十二周】542. 01 Matrix
来源:互联网 发布:seo链轮插件 编辑:程序博客网 时间:2024/05/21 17:37
题目来源:542:https://leetcode.com/problems/01-matrix/description/
BFS基础训练。
- 01 Matrix
- 题目大意
- 思路
- 解题代码
- 时间复杂度
542. 01 Matrix
题目大意
在0/1矩阵中,求出所有元素的距最近0的距离。
例1
Input:
0 0 0
0 1 0
0 0 0Output:
0 0 0
0 1 0
0 0 0例2
Input:
0 0 0
0 1 0
1 1 1Output:
0 0 0
0 1 0
1 2 1
思路
其实本质是求BFS的层数。
做BFS的时候记录层数就可以了。
这里和常规思维有点不同的是,入队的是0。
解题代码
class Solution {public:vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {}};// 点数据结构 struct Point { int x; int y; Point(int _x, int _y) : x(_x), y(_y) {}};// 代表四个方向 int Posx[4] = {-1, 0, 1, 0};int Posy[4] = {0, -1, 0, 1};class Solution {public: bool isValid(int x, int y, vector<vector<int>>& A) { return x >= 0 && x < A.size() && y >= 0 && y < A[x].size(); }vector<vector<int>> updateMatrix(vector<vector<int>>& A) { queue<Point> q1, q2; // 两个保存同节点的队列 int step = 1; // 表示走到0所需的步数,遍历一个队列赋一次值 // 将1更新成-1,即未赋值,将0入队 for (int i = 0; i < A.size(); i++) for (int j = 0; j < A[i].size(); j++) if (A[i][j] == 0) q1.push(Point(i, j));. else A[i][j] = -1; while (!q1.empty() || !q2.empty()) { while (!q1.empty()) { Point p = q1.front(); q1.pop(); // 添加四个方向的节点 for (int i = 0; i < 4; i++) { int newx = p.x + Posx[i]; int newy = p.y + Posy[i]; if (isValid(newx, newy, A) && A[newx][newy] == -1) { A[newx][newy] = step; q2.push(Point(newx, newy)); } } } step++; while (!q2.empty()) { Point p = q2.front(); q2.pop(); // 添加四个方向的节点 for (int i = 0; i < 4; i++) { int newx = p.x + Posx[i]; int newy = p.y + Posy[i]; if (isValid(newx, newy, A) && A[newx][newy] == -1) { A[newx][newy] = step; q1.push(Point(newx, newy)); } } } step++; } return A; }};
时间复杂度
O(rows*cols)
阅读全文
0 0
- 【算法分析与设计】【第十二周】542. 01 Matrix
- 算法分析与设计第十二周:473. Matchsticks to Square
- 算法分析与设计课程06——542. 01 Matrix(Medium)
- [算法分析与设计] leetcode 每周一题: 542. 01 Matrix
- 算法设计与应用基础-第十二周
- 算法设计与应用基础:第十二周
- 第十二周算法分析与设计: Find Largest Value in Each Tree Row
- 算法分析与设计课程作业第十二周#1#2#3#4
- 第二周算法设计与分析:Search a 2D Matrix II
- 算法设计与应用基础:第十二周(1)
- 算法设计与应用基础:第十二周(2)
- 算法设计与结构基础作业第十二周
- 算法分析与设计丨第十二周丨LeetCode(16)——Minimum Path Sum(Medium)
- [算法分析与设计] leetcode 每周一题: Set Matrix Zeroes
- 算法分析与设计
- 算法设计与分析
- 算法分析与设计
- 算法设计与分析
- zookeeper 创建互斥锁的理解
- struts2的常量的编写(五)
- 初学指针
- #pragma使用分析
- C++ this指针
- 【算法分析与设计】【第十二周】542. 01 Matrix
- LightsService分析 --- LED驱动分析
- ADXL362 初次使用总结(使用stm32 HAL 库)
- PAT 1049. Counting Ones (30)(数位dp(记忆化搜索))
- MySQL 的基本使用-1
- Gradle打jar包如何上传到maven本地库
- 算法【】
- 文科生的悲哀
- cpp11 的变量类型自动推断