<?php

$grid = array_map(static function ($row) {
    return str_split($row);
}, explode("\n", file_get_contents('./input.txt')));

$points_in_bassin = [];
$low_points = [];

foreach ($grid as $i => $row) {
    foreach ($row as $j => $cell) {
        $count = 0;
        if (!array_key_exists($i - 1, $grid) || $grid[$i - 1][$j] > $cell) {
            $count++;
        }
        if (!array_key_exists($i + 1, $grid) || $grid[$i + 1][$j] > $cell) {
            $count++;
        }
        if (!array_key_exists($j - 1, $row) || $row[$j - 1] > $cell) {
            $count++;
        }
        if (!array_key_exists($j + 1, $row) || $row[$j + 1] > $cell) {
            $count++;
        }

        if ($count === 4) {
            $low_points[] = [$i, $j];
        }
    }
}

foreach ($low_points as $i => $low_point) {
    $points_in_bassin[$i] = build_bassin($grid, [$low_point],0, [$low_point]);
}

rsort($points_in_bassin);

echo array_product(array_slice($points_in_bassin, 0, 3));

function build_bassin($grid, $neighbours, $count_neighbours = 0, $current_bassin = [])
{
    $step = 0;
    $new_neighbours = [];
    foreach ($neighbours as $value) {
        [$i, $j] = $value;

        if (
            isset($grid[$i][$j - 1]) &&
            $grid[$i][$j - 1] != 9 &&
            !in_array([$i, $j - 1], $current_bassin)
        ) {
            $step++;
            $count_neighbours++;
            $current_bassin[] = [$i, $j - 1];
            $new_neighbours[] = [$i, $j - 1];
        }

        if (
            isset($grid[$i][$j + 1]) &&
            $grid[$i][$j + 1] != 9 &&
            !in_array([$i, $j + 1], $current_bassin)
        ) {
            $step++;
            $count_neighbours++;
            $current_bassin[] = [$i, $j + 1];
            $new_neighbours[] = [$i, $j + 1];
        }

        if (
            isset($grid[$i - 1][$j]) &&
            $grid[$i - 1][$j] != 9 &&
            !in_array([$i - 1, $j], $current_bassin)
        ) {
            $step++;
            $count_neighbours++;
            $current_bassin[] = [$i - 1, $j];
            $new_neighbours[] = [$i - 1, $j];
        }

        if (
            isset($grid[$i + 1][$j]) &&
            $grid[$i + 1][$j] != 9 &&
            !in_array([$i + 1, $j], $current_bassin)
        ) {
            $step++;
            $count_neighbours++;
            $current_bassin[] = [$i + 1, $j];
            $new_neighbours[] = [$i + 1, $j];
        }
    }

    if ($step !== 0) {
        return build_bassin($grid, $new_neighbours, $count_neighbours, $current_bassin, 1);
    }

    return $count_neighbours + 1;
}