Guest User

Untitled

a guest
Dec 8th, 2025
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. private static int part2(char[][] grid) {
  2.     int[][] dp = new int[grid.length][grid[0].length];
  3.    
  4.     for (int i = 1; i < grid.length; i++) {
  5.         for (int j = 0; j < grid[i].length; j++) {
  6.             char current = grid[i][j];
  7.             char above = grid[i-1][j];
  8.  
  9.             // If we have the starting point above us, then emit the beam.
  10.             if (above == 'S') {
  11.                 grid[i][j] = '|';
  12.                 dp[i][j] = 1;
  13.             } else if (current == '^' && above == '|') {
  14.                 // If we see a splitter and have a beam above us,
  15.                 // then split the beam to the left and right of the splitter.
  16.                 if (j-1 >= 0) {
  17.                     grid[i][j-1] = '|';
  18.                     dp[i][j-1] += dp[i-1][j];
  19.                 }
  20.                 if (j+1 < grid[i].length) {
  21.                     grid[i][j+1] = '|';
  22.                     dp[i][j+1] += dp[i-1][j];
  23.                 }
  24.             } else if (above == '|') {
  25.                 // If we're on any other spot and have a beam above us, then continue the beam downward.
  26.                 grid[i][j] = '|';
  27.                 dp[i][j] += dp[i-1][j];
  28.             }
  29.         }
  30.     }
  31.        
  32.     // Sum up all the unique paths at the bottom of the grid.
  33.     int total = 0;
  34.     for (int i = 0; i < dp[0].length; i++) {
  35.         total += dp[dp.length-1][i];
  36.     }
  37.    
  38.     return total;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment