aoc2024

Advent of Code 2024
Log | Files | Refs | README

day10_pt1.java (1678B)


      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_pt1 {
      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 -> tops(grid, th).size()).sum();
     33     System.out.printf("Day 10, pt1: %d\n", res);
     34   }
     35 
     36   static Set<Point> tops(List<String> grid, Point p) {
     37     var val = gv(grid, p);
     38     if (val == 9) {
     39       return Set.of(p);
     40     } else {
     41       return Arrays.stream(DIRS)
     42         .filter(d -> gv(grid, p.add(d)) == val+1)
     43         .flatMap(d -> tops(grid, p.add(d)).stream())
     44         .collect(Collectors.toSet());
     45     }
     46   }
     47 
     48   static int gv(List<String> grid, Point p) {
     49     if (p.y < 0 || p.y >= grid.size()) return -1;
     50     if (p.x < 0 || p.x >= grid.get(0).length()) return -1;
     51     return grid.get(p.y).charAt(p.x) - '0';
     52   }
     53 }