Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function readInput(): array
- {
- $lines = [];
- $f = fopen( 'php://stdin', 'r' );
- while( $line = fgets( $f ) ) {
- $withOutNewLine = str_replace(PHP_EOL,'',$line);
- if ($withOutNewLine != '') {
- $lines[] = $withOutNewLine;
- }
- }
- fclose($f);
- return $lines;
- }
- $input = readInput();
- $grid = [];
- foreach ($input as $line) {
- $grid[] = array_map(fn($item) => intval($item), str_split($line));
- }
- $grid = expandGrid($grid);
- $resp = floodFill(['x' => 0, 'y' => 0], $grid);
- echo $resp . PHP_EOL;
- function expandGrid($grid)
- {
- $w = count($grid[0]);
- $l = count($grid);
- $newW = $w*5;
- $newL = $l*5;
- $newGrid = array_fill(0, $l * 5, array_fill(0, $w * 5, 0));
- for ($i=0; $i < $l; $i++) {
- for ($j=0; $j < $w; $j++) {
- $newGrid[$i][$j] = $grid[$i][$j];
- }
- }
- for ($i=0; $i < $newL; $i++) {
- for ($j=$w; $j < $newW; $j++) {
- $newGrid[$i][$j] = $newGrid[$i][$j-$w] + 1;
- if ($newGrid[$i][$j] > 9) {
- $newGrid[$i][$j] = 1;
- }
- }
- }
- for ($i=$l; $i < $newL; $i++) {
- for ($j=0; $j < $newW; $j++) {
- $newGrid[$i][$j] = $newGrid[$i-$l][$j] + 1;
- if ($newGrid[$i][$j] > 9) {
- $newGrid[$i][$j] = 1;
- }
- }
- }
- return $newGrid;
- }
- function floodFill($startingPoint, $grid) {
- $visited = array_fill(0, count($grid), array_fill(0, count($grid[0]), PHP_INT_MAX));
- $queue = [$startingPoint];
- $visited[0][0] = 0;
- while (count($queue) > 0) {
- $point = array_shift($queue);
- $y = $point['y'];
- $x = $point['x'];
- if ($y - 1 >= 0) {
- if ($visited[$y -1][$x] > $visited[$y][$x] + $grid[$y-1][$x]) {
- $queue[] =
- [
- 'y' => $y-1,
- 'x' => $x
- ];
- $visited[$y -1][$x] = $visited[$y][$x] + $grid[$y-1][$x];
- }
- }
- // down
- if ($y + 1 < count($grid)) {
- if ($visited[$y + 1][$x] > $visited[$y][$x] + $grid[$y+1][$x]) {
- $queue[] = [
- 'y' => $y+1,
- 'x' => $x
- ];
- $visited[$y + 1][$x] = $visited[$y][$x] + $grid[$y+1][$x];
- }
- }
- // left
- if ($x - 1 >= 0) {
- if ($visited[$y][$x-1] > $visited[$y][$x] + $grid[$y][$x-1]) {
- $queue[] = [
- 'y' => $y,
- 'x' => $x-1
- ];
- $visited[$y][$x-1] = $visited[$y][$x] + $grid[$y][$x-1];
- }
- }
- // right
- if ($x + 1 < count($grid[0])) {
- if ($visited[$y][$x+1] > $visited[$y][$x] + $grid[$y][$x+1]) {
- $queue[] = [
- 'y' => $y,
- 'x' => $x+1
- ];
- $visited[$y][$x+1] = $visited[$y][$x] + $grid[$y][$x+1];
- }
- }
- }
- return $visited[count($grid)-1][count($grid[0])-1];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement