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