array_unshift($line, 9), $input); array_unshift($input, array_fill(0, count($input[0]), 9)); $input[] = array_fill(0, count($input[0]), 9); foreach ($lowpoints as $lowpoint) { $searched = []; $input[$lowpoint[0]][$lowpoint[1]] = '*'; getBasinSize($input, $lowpoint[0], $lowpoint[1], $searched); $basinSizes[] = count($searched); } function getBasinSize(&$input, $i, $j, &$searched) { if (!isset($searched[$i . ',' . $j])) { $searched[$i . ',' . $j] = 1; if ($input[$i][$j] != '*') { $input[$i][$j] = ' '; } if ($input[$i - 1][$j] != 9) { getBasinSize($input, $i - 1, $j, $searched); } if ($input[$i][$j - 1] != 9) { getBasinSize($input, $i, $j - 1, $searched); } if ($input[$i][$j + 1] != 9) { getBasinSize($input, $i, $j + 1, $searched); } if ($input[$i + 1][$j] != 9) { getBasinSize($input, $i + 1, $j, $searched); } } } rsort($basinSizes); echo array_product(array_slice($basinSizes, 0, 3)); //970200