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.

思路:BFS错不了,但是一个个点做的话会TLE,想想也是,不同的节点的BFS有一定的重叠,其实完全可以一起BFS遍历啊!
还有值得注意的一点是,给的输入是List,一般都是int[],所以这里就直接用输入,
package l542;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/*
 * do bfs at same time
 * 直接在输入的list对象上更改就好了
 */
public class Solution {
    public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
    	Queue<int[]> q = new LinkedList<int[]>();
    	
    	for(int i=0; i<matrix.size(); i++) {
    		for(int j=0; j<matrix.get(0).size(); j++) {
    			if(matrix.get(i).get(j) == 0) {
    				q.add(new int[]{i, j});
    			} else {
    				matrix.get(i).set(j, -1);	//用来标识是否找到了该点的最短值
    			}
    		}
    	}
    	
    	while(!q.isEmpty()) {
    		int[] cell = q.remove();
    		int x = cell[0], y = cell[1];
			int step = matrix.get(x).get(y);
    		
			if(x > 0 && matrix.get(x-1).get(y) == -1)	{
				q.add(new int[]{x-1, y});
				matrix.get(x-1).set(y, step+1);
			}
			
			if(y > 0 && matrix.get(x).get(y-1) == -1) {
				q.add(new int[]{x, y-1});
				matrix.get(x).set(y-1, step+1);
			}
			
			if(x < matrix.size()-1 && matrix.get(x+1).get(y) == -1)	{
				q.add(new int[]{x+1, y});
				matrix.get(x+1).set(y, step+1);
			}
			
			if(y < matrix.get(0).size()-1 && matrix.get(x).get(y+1) == -1)	{
				q.add(new int[]{x, y+1});
				matrix.get(x).set(y+1, step+1);
			}
    	}
    	
    	return matrix;
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值