$line) { foreach ($line as $column => $number) { // echo ($row + 1) * $i . '-' . ($column + 1) * $j . ' '; $newNumber = ($number + $i + $j); if ($newNumber > 9) { $newNumber++; } $newInput[count($input) * $i + $row][count($input[0]) * $j + $column] = $newNumber%10; } } // echo "\n"; } } $input = $newInput; //foreach ($newInput as $line) { // foreach ($line as $number) { // echo $number . ''; // } //// die(); // echo "\n"; //} //die(); $visited = array_fill(0, count($input), array_fill(0, count($input[0]), PHP_INT_MAX)); $queue = [[0, 0]]; $visited[0][0] = 0; while (count($queue) > 0) { [$x, $y] = array_shift($queue); //down if (isset($input[$x + 1][$y]) && $visited[$x + 1][$y] > $visited[$x][$y] + $input[$x + 1][$y] ) { $queue[] = [$x + 1, $y]; $visited[$x + 1][$y] = $visited[$x][$y] + $input[$x + 1][$y]; } //right if (isset($input[$x][$y + 1]) && $visited[$x][$y + 1] > $visited[$x][$y] + $input[$x][$y + 1] ) { $queue[] = [$x, $y + 1]; $visited[$x][$y + 1] = $visited[$x][$y] + $input[$x][$y + 1]; } } echo $visited[count($visited) - 1][count($visited[0]) - 1]; //553