@@ -80,6 +80,44 @@ func (g *Grid) sumWater(row int) int {
80
80
return sum
81
81
}
82
82
83
+ func (g * Grid ) sumRestWater (row int ) int {
84
+ sum := 0
85
+ for r := g .maxRow ; r >= row ; r -- {
86
+ for c := g .minCol ; c <= g .maxCol ; c ++ {
87
+ unit := g .unitType (Position {r , c })
88
+ if unit != nil && * unit == water && g .isInsideBlock (Position {r , c }, make (map [Position ]struct {})) {
89
+ sum ++
90
+ }
91
+ }
92
+ }
93
+ return sum
94
+ }
95
+
96
+ func (g * Grid ) isInsideBlock (pos Position , visited map [Position ]struct {}) bool {
97
+ unit := g .unitType (pos )
98
+
99
+ if _ , exists := visited [pos ]; exists {
100
+ return true
101
+ }
102
+
103
+ visited [pos ] = struct {}{}
104
+
105
+ if unit == nil {
106
+ return false
107
+ }
108
+
109
+ if * unit == clay {
110
+ return true
111
+ }
112
+
113
+ if * unit == sand {
114
+ return false
115
+ }
116
+
117
+ // Water
118
+ return g .isInsideBlock (pos .delta (0 , - 1 ), visited ) && g .isInsideBlock (pos .delta (0 , 1 ), visited )
119
+ }
120
+
83
121
func (g * Grid ) unitType (current Position ) * UnitType {
84
122
if current .row < g .minRow || current .row > g .maxRow || current .col < g .minCol || current .col > g .maxCol {
85
123
return nil
@@ -318,10 +356,37 @@ func updateScan(s string, scan *Scan) {
318
356
319
357
func fs2 (input io.Reader ) int {
320
358
scanner := bufio .NewScanner (input )
359
+ var scans []Scan
321
360
for scanner .Scan () {
322
- line := scanner .Text ()
323
- _ = line
361
+ scans = append (scans , toScan (scanner .Text ()))
324
362
}
325
363
326
- return 42
364
+ const minRow = 0
365
+ minY := math .MaxInt
366
+ minCol := math .MaxInt
367
+ maxCol := math .MinInt
368
+ maxRow := 0
369
+ for _ , scan := range scans {
370
+ if scan .rangeCol == nil {
371
+ minCol = lib .Min (minCol , scan .col )
372
+ maxCol = lib .Max (maxCol , scan .col )
373
+ } else {
374
+ minCol = lib .Min (minCol , scan .rangeCol .from )
375
+ maxCol = lib .Max (maxCol , scan .rangeCol .to )
376
+ }
377
+
378
+ if scan .rangeRow == nil {
379
+ minY = lib .Min (minY , scan .row )
380
+ maxRow = lib .Max (maxRow , scan .row )
381
+ } else {
382
+ minY = lib .Min (minY , scan .rangeRow .from )
383
+ maxRow = lib .Max (maxRow , scan .rangeRow .to )
384
+ }
385
+ }
386
+
387
+ grid := newGrid (minRow , minCol , maxRow , maxCol , scans )
388
+
389
+ grid .dfs (Position {0 , 500 })
390
+
391
+ return grid .sumRestWater (minY )
327
392
}
0 commit comments