Skip to content

Instantly share code, notes, and snippets.

@doganoo
Created January 5, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doganoo/129e319c8e8e4dd1b6aab86f171b4c1d to your computer and use it in GitHub Desktop.
Save doganoo/129e319c8e8e4dd1b6aab86f171b4c1d to your computer and use it in GitHub Desktop.
count all distinct islands in a 2d array
<?php
function flood(array &$matrix, int $i, int $j) {
$matrix[$i][$j] = 0;
lookupFor($matrix, $i + 1, $j);
lookupFor($matrix, $i, $j + 1);
lookupFor($matrix, $i - 1, $j);
lookupFor($matrix, $i, $j - 1);
}
function lookupFor(array &$matrix, int $i, int $j) {
$iSize = count($matrix);
if (inRange($i, 0, $iSize)) {
$jSize = count($matrix[$i]);
if (inRange($j, 0, $jSize)) {
if (isIslandCell($matrix[$i][$j])) {
flood($matrix, $i, $j);
}
}
}
}
function isIslandCell(int $val) {
return 1 === $val;
}
function inRange(int $i, int $start, int $end) {
return $i >= $start && $i < $end;
}
function countIslands(array $matrix) {
$islandCount = 0;
$iSize = count($matrix);
for ($i = 0; $i < $iSize; $i++) {
$jSize = count($matrix[$i]);
for ($j = 0; $j < $jSize; $j++) {
if (isIslandCell($matrix[$i][$j])) {
$islandCount++;
flood($matrix, $i, $j);
}
}
}
return $islandCount;
}
$matrix = [];
$matrix[] = [0, 0, 0, 1];
$matrix[] = [0, 0, 0, 0];
$matrix[] = [1, 0, 1, 0];
$matrix[] = [1, 1, 1, 0];
echo countIslands($matrix);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment