|
| 1 | +package algo |
| 2 | + |
| 3 | +func openLock(deadends []string, target string) int { |
| 4 | + type Node struct { |
| 5 | + Number string |
| 6 | + Move int |
| 7 | + } |
| 8 | + visited := map[string]bool{} |
| 9 | + q := []Node{{ |
| 10 | + Number: "0000", |
| 11 | + Move: 0, |
| 12 | + }} |
| 13 | + |
| 14 | + deadendMap := map[string]bool{} |
| 15 | + for _, deadend := range deadends { |
| 16 | + deadendMap[deadend] = true |
| 17 | + } |
| 18 | + if len(deadends) >= 8 && checkDeadlock(deadendMap, target) { |
| 19 | + return -1 |
| 20 | + } |
| 21 | + |
| 22 | + for len(q) > 0 { |
| 23 | + // TODO: 什麼時候要+ move |
| 24 | + cursor := q[0] |
| 25 | + q = q[1:] |
| 26 | + visited[cursor.Number] = true |
| 27 | + |
| 28 | + if _, ok := deadendMap[cursor.Number]; ok { |
| 29 | + continue |
| 30 | + } |
| 31 | + if cursor.Number == target { |
| 32 | + return cursor.Move |
| 33 | + } |
| 34 | + |
| 35 | + neighbors := findNeighbors(cursor.Number) |
| 36 | + for _, neighbor := range neighbors { |
| 37 | + q = append(q, Node{Number: neighbor, Move: cursor.Move + 1}) |
| 38 | + } |
| 39 | + } |
| 40 | + return -1 |
| 41 | +} |
| 42 | + |
| 43 | +func findNeighbors(cursor string) []string { |
| 44 | + neighbors := []string{} |
| 45 | + for i := 0; i < len(cursor); i++ { |
| 46 | + c := int(cursor[i]) |
| 47 | + if c == 48 { |
| 48 | + neighbors = append(neighbors, cursor[0:i]+"1"+cursor[i+1:]) |
| 49 | + neighbors = append(neighbors, cursor[0:i]+"9"+cursor[i+1:]) |
| 50 | + } else { |
| 51 | + neighbors = append(neighbors, cursor[0:i]+string(rune(c+1))+cursor[i+1:]) |
| 52 | + neighbors = append(neighbors, cursor[0:i]+string(rune(c-1))+cursor[i+1:]) |
| 53 | + } |
| 54 | + } |
| 55 | + return neighbors |
| 56 | +} |
| 57 | + |
| 58 | +func checkDeadlock(deadendMap map[string]bool, target string) bool { |
| 59 | + |
| 60 | + neighbors := findNeighbors(target) |
| 61 | + for _, neighbor := range neighbors { |
| 62 | + if _, ok := deadendMap[neighbor]; !ok { |
| 63 | + return false |
| 64 | + } |
| 65 | + } |
| 66 | + return true |
| 67 | +} |
0 commit comments