第十周LeetCode
来源:互联网 发布:淘宝50字好评 编辑:程序博客网 时间:2024/06/07 01:21
题目
难度 medium
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 0
Output:
0 0 0
0 1 0
0 0 0Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1Note:
1.The number of elements of the given matrix will not exceed 10,000.
2.There are at least one 0 in the given matrix.
3.The cells are adjacent in only four directions: up, down, left and right.
实现思路
可以用bfs实现,将ans[i][j]看成与最近的0的距离。先将矩阵元素不为0的位置值设为-1标记其未访问,然后将矩阵元素为0的坐标位置(i,j)入队。访问队列的队头,则其未被访问的相邻点(上下左右)的距离为ans[i][j]+1,并将其未被访问的相邻点坐标入队,直到队列为空。
实现代码
//储存坐标struct Node{ int x; int y; Node(int X, int Y) { x = X; y = Y; } };class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int> > &a) { queue<Node> q ; vector<vector<int>> ans = a ; for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a[i].size(); j++) { if (a[i][j] == 0) { q.push(Node(i, j)); } else { ans[i][j] = -1; } } } Node dire[4] = {Node(-1,0),Node(1,0),Node(0,-1),Node(0,1)}; while (!q.empty()) { Node node = q.front(); int x = node.x; int y = node.y; q.pop(); for (int i = 0; i < 4; i++) { int cur_x = x+dire[i].x; int cur_y = y+dire[i].y; //注意防止越界 if (cur_x >= 0 && cur_x < a.size() && cur_y >=0 && cur_y < a[cur_x].size() && ans[cur_x][cur_y]==-1) { ans[cur_x][cur_y] = ans[x][y]+1; q.push(Node(cur_x,cur_y)); } } } return ans; }};
阅读全文
0 0
- leetcode-python 第十周
- leetcode-第十周
- 第十周leetcode题
- [leetcode]第十周作业
- 第十周LeetCode
- LeetCode题解 第十周
- leetcode【第十周】数字组合
- leetcode第十周解题总结
- 第十周LeetCode算法题两道
- Leetcode 算法习题 第十周
- 第十周:[leetCode] 72. Edit Distance
- 第十周:[Leetcode]486. Predict the Winner
- leetcode算法课程第十周博客
- leetcode-python 第十一周
- leetcode-python 第十四周
- leetcode-第十一周
- leetcode-第十四周
- 第十四周leetcode题
- 14 个你可能不知道的 JavaScript 调试技巧
- 一个类文件如何继承其它文件的类?
- 朴素贝叶斯学习 续2
- unity 《专题系列》资源打包 Asset Bundles 第三节 Asset Bundles 加载
- webpack知识学习第2天,配置类型 条目和上下文 输出
- 第十周LeetCode
- SQL limit offset
- 【C语言】找出一个字符串中第一个只出现一次的字符
- 在linux服务器部署git仓库
- 6.5华氏温度
- 浏览器兼容性问题
- Mysql| 组合where子句过滤数据(AND,OR,IN,NOT)
- C++ 编程小问题
- 华氏度与摄氏度对照表