Java解决 01 矩阵问题

题目描述

题目来源于leetcod:https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/892/

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1:
输入:

0 0 0
0 1 0
0 0 0
输出:

0 0 0
0 1 0
0 0 0
示例 2:
输入:

0 0 0
0 1 0
1 1 1
输出:

0 0 0
0 1 0
1 2 1
注意:

给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。

分析

此题和墙与门问题几乎一模一样,从0开始进行广度优先遍历,将0四周是1的值置为当前层数+1,但不同的是,由于矩阵是0、1,而1本身又是一个解答会得到的值,所以,为了防止死循环,我们将坐标为1的值改为-1。

更详细的解答可以参考墙与门问题:https://blog.csdn.net/admite/article/details/107289151

代码

class Solution {
    private List<int[]> action = Arrays.asList(
			new int[] {0,1},
			new int[] {0,-1},
			new int[] {1,0},
			new int[] {-1,0}
	);
	public int[][] updateMatrix(int[][] matrix) {
		if(matrix == null || matrix.length==0) {
			return matrix;
		}
		int l_length = matrix.length;
		int v_length = matrix[0].length;
		LinkedList<int[]> list = new LinkedList<>();
		for(int i=0;i<l_length;i++) {
			for(int j=0;j<v_length;j++) {
				if(matrix[i][j]==0) {
					list.add(new int[] {i,j});
				}
				if(matrix[i][j]==1) {
					matrix[i][j] = -1;
				}
			}
		}
		while(!list.isEmpty()) {
			int[] x = list.poll();
			int a = x[0];
			int b = x[1];
			for(int[] y:action) {
				int m = a + y[0];
				int n = b + y[1];
				if(m<0 || m>l_length-1 || n<0 || n>v_length-1 || matrix[m][n]!=-1) {
					continue;
				}
				matrix[m][n] = matrix[a][b] + 1;
				list.add(new int[] {m,n});
			}
		}
		return matrix;
		
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值