LeetCode 542----01 Matrix
2017-03-19 11:07
357 查看
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 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1
Output:
0 0 0 0 1 0 1 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.
算法分析
遍历原矩阵,将值为0的位置的坐标(i,j)加入队列Queue
Java 算法实现:
public class Solution { static class Pair{ public int i; public int j; Pair(int i,int j){ this.i=i; this.j=j; } } public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) { int n=matrix.size(); int m=matrix.get(0).size(); List<List<Integer>>list=new ArrayList<>(); int longest=n*m; Queue<Pair>queue=new LinkedList<>(); for(int i=0;i<n;i++){ List<Integer>tmp=new ArrayList<>(); List<Integer>ori=matrix.get(i); for(int j=0;j<m;j++){ if(ori.get(j)==0){ queue.add(new Pair(i, j)); tmp.add(0); } else{ tmp.add(longest); } } list.add(tmp); } int [][]dir={{-1,0},{1,0},{0,-1},{0,1}}; while(!queue.isEmpty()){ Pair pair=queue.poll(); int i=pair.i; int j=pair.j; int dist=list.get(i).get(j); for(int k=0;k<4;k++){ int ii=i+dir[k][0]; int jj=j+dir[k][1]; if(ii>=0&&ii<n&&jj>=0&&jj<m){ if(list.get(ii).get(jj)>dist+1){ list.get(ii).set(jj, dist+1); queue.add(new Pair(ii, jj)); } } } } return list; } }
相关文章推荐
- 【LeetCode】542. 01 Matrix
- [leetcode]542. 01 Matrix
- LeetCode - 542 - 01 Matrix
- [Leetcode] #542 01 Matrix (BFS)
- 542. 01 Matrix [LeetCode]
- leetcode-542-01 Matrix
- Leetcode 542. 01 Matrix(BFS)
- [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 距离0最近的距离 + 正反遍历 + 动态规划DP
- LeetCode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- LeetCode-542. 01 Matrix (JAVA)零一矩阵
- leetcode 542. 01 Matrix
- [LeetCode]542. 01 Matrix
- [LeetCode] 542. 01 Matrix