aoc2024

Advent of Code 2024
Log | Files | Refs | README

day10_pt2.java (1634B)


      1 import java.nio.file.Files;
      2 import java.nio.file.Path;
      3 import java.io.IOException;
      4 import java.util.*;
      5 import java.util.stream.*;
      6 
      7 public class day10_pt2 {
      8   record Point(int x, int y) {
      9     Point add(Vec v) {
     10       return new Point(this.x + v.x, this.y + v.y);
     11     }
     12   }
     13   record Vec(int x, int y) {}
     14   private static final Vec[] DIRS = new Vec[]{new Vec( 0, 1),
     15                                               new Vec( 1, 0),
     16                                               new Vec( 0,-1),
     17                                               new Vec(-1, 0)};
     18   public static void main(String[] args) throws IOException {
     19     var grid = Files.readAllLines(Path.of(args[0]));
     20     var trailheads = new ArrayList<Point>();
     21     var height = grid.size();
     22     var width = grid.get(0).length();
     23     // pass 1 find trailheads
     24     for (int y=0; y<height; y++) {
     25       for (int x=0; x<width; x++) {
     26         var val = gv(grid, new Point(x, y));
     27         if (val == 0) {
     28           trailheads.add(new Point(x, y));
     29         }
     30       }
     31     }
     32     var res = trailheads.stream().mapToInt(th -> rating(grid, th)).sum();
     33     System.out.printf("Day 10, pt2: %d\n", res);
     34   }
     35   
     36   static int gv(List<String> grid, Point p) {
     37     if (p.y < 0 || p.y >= grid.size()) return -1;
     38     if (p.x < 0 || p.x >= grid.get(0).length()) return -1;
     39     return grid.get(p.y).charAt(p.x) - '0';
     40   }
     41 
     42   static int rating(List<String> grid, Point p) {
     43     var val = gv(grid, p);
     44     if (val == 9) {
     45       return 1;
     46     } else {
     47       return Arrays.stream(DIRS)
     48         .filter(d -> gv(grid, p.add(d)) == val+1)
     49         .mapToInt(d -> rating(grid, p.add(d)))
     50         .sum();
     51     }
     52   }
     53 }