11package main
22
3- import (
4- "fmt"
5-
6- "github.com/lucianoq/container/set"
7- )
3+ import "fmt"
84
95func main () {
10- m , p , dir := parseMap ()
6+ m , pos , dir := parseMap ()
7+
8+ visited := run (m , pos , dir )
119
1210 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- }
11+ for obstacle := range visited {
12+ if testObstacle (m , obstacle , pos , dir ) {
13+ count ++
1814 }
1915 }
20-
2116 fmt .Println (count )
2217}
2318
24- type State struct {
19+ type status struct {
2520 Pos P
26- Dir uint8
21+ Dir Direction
2722}
2823
29- func testObstacle (m map [P ]struct {}, obstacle , pos P , dir uint8 ) bool {
24+ func testObstacle (m map [P ]struct {}, obstacle P , pos P , dir Direction ) bool {
3025
3126 // impossible if the guard is there
3227 if obstacle == pos {
@@ -43,22 +38,12 @@ func testObstacle(m map[P]struct{}, obstacle, pos P, dir uint8) bool {
4338 delete (m , obstacle )
4439 }()
4540
46- visited := set.Set [State ]{}
47- visited .Add (State {pos , dir })
41+ visited := map [status ]struct {}{
42+ status {pos , dir }: {},
43+ }
4844
4945 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- }
46+ next := pos .Next (dir )
6247
6348 if next .x < 0 || next .x >= Size || next .y < 0 || next .y >= Size {
6449 return false
@@ -70,10 +55,10 @@ func testObstacle(m map[P]struct{}, obstacle, pos P, dir uint8) bool {
7055 pos = next
7156 }
7257
73- newState := State {pos , dir }
74- if visited . Contains ( newState ) {
58+ st := status {pos , dir }
59+ if _ , ok := visited [ st ]; ok {
7560 return true
7661 }
77- visited . Add ( newState )
62+ visited [ st ] = struct {}{}
7863 }
7964}
0 commit comments