Skip to content

Commit 8d18777

Browse files
author
Shuo
authored
Merge pull request #638 from openset/develop
Add: 01 Matrix
2 parents c84a624 + df1e8c3 commit 8d18777

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Diff for: problems/01-matrix/01_matrix.go

+42
Original file line numberDiff line numberDiff line change
@@ -1 +1,43 @@
11
package p_01_matrix
2+
3+
func updateMatrix(matrix [][]int) [][]int {
4+
m, n := len(matrix), len(matrix[0])
5+
MIN := m * n
6+
// 根据 左方 和 上方 的格子,更新 (i,j)
7+
for i := 0; i < m; i++ {
8+
for j := 0; j < n; j++ {
9+
if matrix[i][j] == 0 {
10+
continue
11+
}
12+
matrix[i][j] = MIN
13+
if 0 <= i-1 {
14+
matrix[i][j] = min(matrix[i][j], matrix[i-1][j]+1)
15+
}
16+
if 0 <= j-1 {
17+
matrix[i][j] = min(matrix[i][j], matrix[i][j-1]+1)
18+
}
19+
}
20+
}
21+
// 根据 右方 和 下方 的格子,更新 (i,j)
22+
for i := m - 1; 0 <= i; i-- {
23+
for j := n - 1; 0 <= j; j-- {
24+
if matrix[i][j] == 0 {
25+
continue
26+
}
27+
if i+1 < m {
28+
matrix[i][j] = min(matrix[i][j], matrix[i+1][j]+1)
29+
}
30+
if j+1 < n {
31+
matrix[i][j] = min(matrix[i][j], matrix[i][j+1]+1)
32+
}
33+
}
34+
}
35+
return matrix
36+
}
37+
38+
func min(a, b int) int {
39+
if a < b {
40+
return a
41+
}
42+
return b
43+
}

Diff for: problems/01-matrix/01_matrix_test.go

+45
Original file line numberDiff line numberDiff line change
@@ -1 +1,46 @@
11
package p_01_matrix
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input [][]int
10+
expected [][]int
11+
}
12+
13+
func TestUpdateMatrix(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: [][]int{
17+
{0, 0, 0},
18+
{0, 1, 0},
19+
{0, 0, 0},
20+
},
21+
expected: [][]int{
22+
{0, 0, 0},
23+
{0, 1, 0},
24+
{0, 0, 0},
25+
},
26+
},
27+
{
28+
input: [][]int{
29+
{0, 0, 0},
30+
{0, 1, 0},
31+
{1, 1, 1},
32+
},
33+
expected: [][]int{
34+
{0, 0, 0},
35+
{0, 1, 0},
36+
{1, 2, 1},
37+
},
38+
},
39+
}
40+
for _, tc := range tests {
41+
output := updateMatrix(tc.input)
42+
if !reflect.DeepEqual(output, tc.expected) {
43+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)