Skip to content

Commit cf02987

Browse files
committed
feat(leetcode): add No.1091
1 parent ce73328 commit cf02987

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// https://leetcode.com/problems/shortest-path-in-binary-matrix/
2+
//
3+
// algorithms
4+
// Medium (35.69%)
5+
// Total Accepted: 3,868
6+
// Total Submissions: 10,837
7+
// beats 100.0% of golang submissions
8+
9+
package leetcode
10+
11+
type point struct {
12+
i int
13+
j int
14+
sum int
15+
}
16+
17+
func shortestPathBinaryMatrix(grid [][]int) int {
18+
length := len(grid)
19+
delta := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}
20+
21+
if grid[0][0] == 1 {
22+
return -1
23+
}
24+
25+
if length == 1 {
26+
return 1
27+
}
28+
29+
var q []point
30+
q = append(q, point{
31+
i: 0,
32+
j: 0,
33+
sum: 1,
34+
})
35+
36+
for len(q) > 0 {
37+
curP := q[0]
38+
q = q[1:]
39+
for _, d := range delta {
40+
if checkPosition(curP.i+d[0], curP.j+d[1], length, grid) {
41+
nextI, nextJ := curP.i+d[0], curP.j+d[1]
42+
if nextI == length-1 && nextJ == length-1 {
43+
return curP.sum + 1
44+
}
45+
q = append(q, point{
46+
i: nextI,
47+
j: nextJ,
48+
sum: curP.sum + 1,
49+
})
50+
grid[nextI][nextJ] = 1
51+
}
52+
}
53+
}
54+
55+
return -1
56+
}
57+
58+
func checkPosition(i, j, length int, grid [][]int) bool {
59+
if i < 0 || i >= length || j < 0 || j >= length || grid[i][j] == 1 {
60+
return false
61+
}
62+
63+
return true
64+
}

0 commit comments

Comments
 (0)