Solution of Matrix

本文介绍了一种算法,用于寻找矩阵中每个元素到最近0的距离。通过两次迭代,利用四个方向上的相邻元素,实现了O(n^2)的时间复杂度和O(n)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.

Ideas of solving problems

When solving this problem, we should pay attention to its boundary range.We can use two loops to search for the distance of each element to the nearest 0.Because the distance between two adjacent elements is 1, so if the three sides of a number are 1, and the diagonal is 0.So the distance between this number and 0 is 2.So we can figure out the final answer in two iterations. The time complexity is O(n^2), and the space complexity is O(n). The memory consumption is 7Mb.

Code

package main

import (
	"fmt"
)
func main(){
	matrix := [] [] int {{0,0,0},{0,1,0},{0,0,0}}
	fmt.Println(updateMatrix(matrix))
}
func min(a, b int) int {
	if a <= b {
		return a
	}
	return b
}

func updateMatrix(matrix [][]int) [][]int {
	m, n := len(matrix), len(matrix[0])
	res := make([][]int, m)
	for i := 0; i < m; i++ {
		res[i] = make([]int, n)
		for j := 0; j < n; j++ {
			if matrix[i][j] != 0 {
				res[i][j] = 10000
				if i != 0 {
					res[i][j] = min(res[i][j], res[i-1][j]+1)
				}
				if j != 0 {
					res[i][j] = min(res[i][j], res[i][j-1]+1)
				}
			} else {
				res[i][j] = 0
			}
		}
	}
	for i := m - 1; i >= 0; i-- {
		for j := n - 1; j >= 0; j-- {
			if res[i][j] > 1 {
				if i < m-1 {
					res[i][j] = min(res[i][j], res[i+1][j]+1)
				}
				if j < n-1 {
					res[i][j] = min(res[i][j], res[i][j+1]+1)
				}
			}
		}
	}
	return res
}


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/01-matrix

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值