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.Example 1:
Input:
Output:
0 0 0 0 1 0 0 0 0Example 2:
Input:
Output:
0 0 0 0 1 0 1 2 1Note:
- 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;
}
}