zoukankan      html  css  js  c++  java
  • 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;
        }
        
    }
  • 相关阅读:
    JavaScript 闭包
    JavaScript Ajax
    JQuery简介
    NYOJ--491--dfs(打表水过)--幸运三角形
    素数环:NYOJ--488--dfs||hdu-1016-Prime Ring Problem
    NYOJ--353--bfs+优先队列--3D dungeon
    NYOJ--325--深度优先搜索--zb的生日
    NYOJ--202--红黑树
    第一个Android程序
    Vmware虚拟机安装win7系统教程
  • 原文地址:https://www.cnblogs.com/dongling/p/6579704.html
Copyright © 2011-2022 走看看