<?php

$grid = array_map('str_split', explode("\n", file_get_contents('./input.txt')));

$flashes = 0;

for ($i = 0; $i < 100; $i++) {
    foreach ($grid as $k => $row) {
        foreach ($row as $j => $cell) {
            $grid[$k][$j]++;
        }
    }

    while(has_more_than_nine($grid)) {
        foreach ($grid as $k => $row) {
            foreach ($row as $j => $cell) {
                if ($grid[$k][$j] > 9) {
                    foreach (range(-1, 1) as $r) {
                        foreach (range(-1, 1) as $c) {
                            if ($r === 0 && $c === 0) {
                                $grid[$k+$r][$j+$c] = 0;
                            }
                            if (
                                array_key_exists($k+$r, $grid) &&
                                array_key_exists($j+$c, $grid[$k+$r]) &&
                                $grid[$k+$r][$j+$c] !== 0
                            ) {
                                $grid[$k+$r][$j+$c]++;
                            }
                        }
                    }
                    $flashes++;
                }
            }
        }
    }

    echo sprintf('After step %u%s%s%s', $i + 1, "\n", implode("\n", array_map('implode', $grid)), "\n", "\n");
}

echo $flashes;

function has_more_than_nine($grid)
{
    foreach ($grid as $row) {
        foreach ($row as $cell) {
            if ($cell > 9) {
                return true;
            }
        }
    }

    return false;
}