40 lines
856 B
Go
40 lines
856 B
Go
package q1926
|
|
|
|
const (
|
|
EMPTY byte = '.'
|
|
WALL byte = '+'
|
|
)
|
|
|
|
func nearestExit(maze [][]byte, entrance []int) int {
|
|
queue := make([][3]int, 0, len(maze)) // row, col, step
|
|
queue = append(queue, [3]int{entrance[0], entrance[1], 0})
|
|
maze[entrance[0]][entrance[1]] = WALL // mark as visited
|
|
|
|
var add = func(r, c, s int) bool {
|
|
if r < 0 || c < 0 || r >= len(maze) || c >= len(maze[0]) || maze[r][c] != EMPTY {
|
|
return false
|
|
}
|
|
|
|
if r == 0 || c == 0 || r == len(maze)-1 || c == len(maze[0])-1 {
|
|
return true // found
|
|
}
|
|
|
|
maze[r][c] = WALL
|
|
queue = append(queue, [3]int{r, c, s})
|
|
return false
|
|
}
|
|
|
|
for ; len(queue) > 0; queue = queue[1:] {
|
|
cur := queue[0]
|
|
r, c, s := cur[0], cur[1], cur[2]
|
|
if add(r, c+1, s+1) ||
|
|
add(r, c-1, s+1) ||
|
|
add(r+1, c, s+1) ||
|
|
add(r-1, c, s+1) {
|
|
return s + 1
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
var _ = nearestExit
|