1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| func shortestPathBinaryMatrix(grid [][]int) int { n := len(grid) if grid[0][0] == 1 { return -1 } if n == 1 { return 1 }
q := [][]int{} visited := make([][]bool, n)
for i := 0; i < n; i++ { visited[i] = make([]bool, n) } visited[0][0] = true
ans := -1 var bfs func() var valid func(int, int) bool
q = append(q, []int{0, 0, 1})
bfs = func() { for len(q) > 0 { curr := q[0] q = q[1:]
dx := []int{1, 1, 0, -1, 1, 0, -1, -1} dy := []int{1, 0, 1, 1, -1, -1, 0, -1}
for i := 0; i < 8; i++ { row := curr[0] + dy[i] col := curr[1] + dx[i]
if valid(row, col) { visited[row][col] = true if row == n-1 && col == n-1 { ans = curr[2] + 1 } q = append(q, []int{row, col, curr[2] + 1}) } } } }
valid = func(row, col int) bool { if row < 0 || col < 0 || row >= n || col >= n || visited[row][col] { return false }
return grid[row][col] == 0 }
bfs() return ans }
func powInt(x, y int) int { return int(math.Pow(float64(x), float64(y))) }
|