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:

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)加入队列Queuequeue当中,然后对queue中的每一个Pair,考察其临近的四个位置,如果临近的四个位置到0的距离可以更新,就进行更新,并将进行了更新的位置的坐标(ii,jj)加入队列 queue 里。持续上述过程知道 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;
    }
    
}
posted on 2017-03-19 11:07  HorseShoe2016  阅读(367)  评论(0编辑  收藏  举报