-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path864. Shortest Path to Get All Keys.go
64 lines (62 loc) · 1.38 KB
/
864. Shortest Path to Get All Keys.go
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
63
64
package main
import (
"strconv"
"unicode"
)
func shortestPathAllKeys(grid []string) int {
move := [5]int{0, 1, 0, -1, 0}
sx := -1
sy := -1
m := len(grid)
n := len(grid[0])
numKeys := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == '@' {
sx = i
sy = j
} else if unicode.IsLower(rune(grid[i][j])) {
numKeys++
}
}
}
queue := make([][]int, 0, m*n)
visited := make(map[string]bool)
cur := strconv.Itoa(0) + " " + strconv.Itoa(sx) + "/" + strconv.Itoa(sy)
print(cur)
visited[cur] = true
queue = append(queue, []int{0, sx, sy})
step := 0
for len(queue) > 0 {
size := len(queue)
for i := 0; i < size; i++ {
temp := queue[i]
if temp[0] == (1<<uint(numKeys) - 1) {
return step
}
for j := 0; j < 4; j++ {
nx := temp[1] + move[j]
ny := temp[2] + move[j+1]
keys := temp[0]
if nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] != '#' {
if unicode.IsLower(rune(grid[nx][ny])) {
keys |= 1 << uint(grid[nx][ny]-'a')
}
if unicode.IsUpper(rune(grid[nx][ny])) {
if (keys>>uint(grid[nx][ny]-'A'))&1 == 0 {
continue
}
}
status := strconv.Itoa(keys) + " " + strconv.Itoa(nx) + "/" + strconv.Itoa(ny)
if !visited[status] {
visited[status] = true
queue = append(queue, []int{keys, nx, ny})
}
}
}
}
queue = queue[size:]
step++
}
return -1
}