542. 01 Matrix
来源:互联网 发布:intel芯片组驱动linux 编辑:程序博客网 时间:2024/06/06 10:50
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 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
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.
Subscribe to see which companies asked this question.
Solution:
Tips:
iterator matrix from left up corner to right down. then from right down to left up.
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1, dp[i + 1][j] + 1, dp[i][j + 1] + 1, dp[i] [j - 1] + 1);
Java Code:
public class Solution { public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) { List<List<Integer>> result = new ArrayList<>(); if (null == matrix) { return result; } int m = matrix.size(); int n = matrix.get(0).size(); int maxDistance = m * n; int[][] distance = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { distance[i][j] = matrix.get(i).get(j) == 0 ? 0 : maxDistance; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { distance[i][j] = i - 1 >= 0 ? Math.min(distance[i - 1][j] + 1, distance[i][j]) : distance[i][j]; distance[i][j] = j - 1 >= 0 ? Math.min(distance[i][j - 1] + 1, distance[i][j]) : distance[i][j]; } } for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { distance[i][j] = i + 1 < m ? Math.min(distance[i + 1][j] + 1, distance[i][j]) : distance[i][j]; distance[i][j] = j + 1 < n ? Math.min(distance[i][j + 1] + 1, distance[i][j]) : distance[i][j]; } } for (int i = 0; i < m; i++) { List<Integer> lst = new ArrayList<>(); for (int j = 0; j < n; j++) { lst.add(distance[i][j]); } result.add(lst); } return result; }}
0 0
- 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
- 542. 01 Matrix
- 542. 01 Matrix 题解
- [leetcode]542. 01 Matrix
- 【LeetCode】542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix [LeetCode]
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- 05-树9 Huffman Codes (30分)
- C语言指针数组
- Matlab 数值计算----牛顿法解非线性方程组
- Cleanflight文档——PID 整定
- viewPager的简单实现
- 542. 01 Matrix
- RecyclerView整体思路分析
- jvm内存管理与gc
- 【数据结构笔记】3:无向图的邻接矩阵存储结构
- jQuery(三)常规选择器
- 源码编译安装程序
- python中uuid来生成机器唯一标识
- linux压缩与解压缩
- 在浏览器中输入 Google.com 回车之后发生了什么?