|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/lucianoq/container/set" |
| 7 | +) |
| 8 | + |
| 9 | +func main() { |
| 10 | + m, p, dir := parseMap() |
| 11 | + |
| 12 | + var count int |
| 13 | + for i := 0; i < Size; i++ { |
| 14 | + for j := 0; j < Size; j++ { |
| 15 | + if testObstacle(m, P{i, j}, p, dir) { |
| 16 | + count++ |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + fmt.Println(count) |
| 22 | +} |
| 23 | + |
| 24 | +type State struct { |
| 25 | + Pos P |
| 26 | + Dir uint8 |
| 27 | +} |
| 28 | + |
| 29 | +func testObstacle(m map[P]any, obstacle, pos P, dir uint8) bool { |
| 30 | + |
| 31 | + // impossible if the guard is there |
| 32 | + if obstacle == pos { |
| 33 | + return false |
| 34 | + } |
| 35 | + |
| 36 | + // impossible if there is already an obstacle there |
| 37 | + if _, ok := m[obstacle]; ok { |
| 38 | + return false |
| 39 | + } |
| 40 | + |
| 41 | + m[obstacle] = struct{}{} |
| 42 | + defer func() { |
| 43 | + delete(m, obstacle) |
| 44 | + }() |
| 45 | + |
| 46 | + visited := set.Set[State]{} |
| 47 | + visited.Add(State{pos, dir}) |
| 48 | + |
| 49 | + for { |
| 50 | + var next P |
| 51 | + |
| 52 | + switch dir { |
| 53 | + case N: |
| 54 | + next = P{pos.x - 1, pos.y} |
| 55 | + case E: |
| 56 | + next = P{pos.x, pos.y + 1} |
| 57 | + case S: |
| 58 | + next = P{pos.x + 1, pos.y} |
| 59 | + case W: |
| 60 | + next = P{pos.x, pos.y - 1} |
| 61 | + } |
| 62 | + |
| 63 | + if next.x < 0 || next.x >= Size || next.y < 0 || next.y >= Size { |
| 64 | + return false |
| 65 | + } |
| 66 | + |
| 67 | + if _, ok := m[next]; ok { |
| 68 | + dir = (dir + 1) % 4 |
| 69 | + } else { |
| 70 | + pos = next |
| 71 | + } |
| 72 | + |
| 73 | + newState := State{pos, dir} |
| 74 | + if visited.Contains(newState) { |
| 75 | + return true |
| 76 | + } |
| 77 | + visited.Add(newState) |
| 78 | + } |
| 79 | +} |
0 commit comments