您的位置:首页 > 其它

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:

  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.

算法分析

遍历原矩阵,将值为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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: