【LeetCode】542. 01 Matrix
来源:互联网 发布:本地系统 网络受限 编辑:程序博客网 时间:2024/06/13 02:35
【LeetCode】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.
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.
【输入输出】
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
【解题思路】
动态规划(DP):
1. ans[i][j] 存储到0的最少步数,flag记录上次循环是否有更新ans
2. 如果M[i][j] == 0, 则ans[i][j]=0; 否则为一步可达所有位置的ans最小值加一,即ans[i][j] = min(ans[i][j], 1+min(min((j > 0)?ans[i][j-1]:con, (j < col-1)?ans[i][j+1]:con), min((i > 0)?ans[i-1][j]:con, (i < row-1)?ans[i+1][j]:con)));
3. 返回ans
【代码】
class Solution {public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int row = matrix.size(), col = matrix[0].size(), flag = 1, con = 10001; vector<vector<int>> ans(row, vector<int>(col, con)); while(flag == 1) { flag = 0; for(int i = 0;i < row;i++) { for(int j = 0;j < col;j++) { int last = ans[i][j]; if(matrix[i][j] == 0) ans[i][j] = 0; else ans[i][j] = min(ans[i][j], 1+min(min((j > 0)?ans[i][j-1]:con, (j < col-1)?ans[i][j+1]:con), min((i > 0)?ans[i-1][j]:con, (i < row-1)?ans[i+1][j]:con))); if(ans[i][j] != last) flag = 1; } } } return ans; }};
阅读全文
0 0
- Leetcode-542. 01 Matrix
- [LeetCode]542. 01 Matrix
- leetcode 542. 01 Matrix
- [leetcode]542. 01 Matrix
- 【LeetCode】542. 01 Matrix
- 542. 01 Matrix [LeetCode]
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- 【leetcode】542. 01 Matrix的解法总结
- [Leetcode] 542. 01 Matrix 解题报告
- leetcode-542-01 Matrix
- [LeetCode.542]01 Matrix
- LeetCode之01 Matrix
- LeetCode--01 Matrix
- 【LeetCode】01 Matrix 解题报告
- [Leetcode] #542 01 Matrix (BFS)
- 状态设计模式
- 《算法设计与分析基础 第二版》pdf
- 学习淘淘商城第七十八课(LVS+Nginx负载均衡(包括两种开机启动方法)----中篇)
- DeepLearning(基于caffe)实战项目(8)--修改caffe源代码从添加loss(层)函数开始
- oracle 12c R2 rac安装
- 【LeetCode】542. 01 Matrix
- 归并排序
- IntelliJ Idea 常用快捷键列表
- Lua知识点九
- 你真的懂Handler.postDelayed()的原理吗?
- 《算法心得-高效算法的奥秘(原书第2版)》pdf
- 学习记录
- POJ 3186 Treats for the Cows(区间DP)
- Invoking Page() in async task.