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));
- }
- $resp = floodFill(['x' => 0, 'y' => 0], $grid);
- echo $resp . PHP_EOL;
- 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