Skip to content

Instantly share code, notes, and snippets.

@doganoo
Last active November 14, 2020 19:00
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/6a35074b1367ab628219370da6e891ab to your computer and use it in GitHub Desktop.
Save doganoo/6a35074b1367ab628219370da6e891ab to your computer and use it in GitHub Desktop.
Leetcode: 200. Number of Islands
<?php
function numIslands(array $grid):int {
$length = count($grid);
$islandCount = 0;
if ($length === 0) {
return 0;
}
for ($i = 0; $i < $length; $i++) {
$jCount = count($grid[$i]);
for ($j = 0; $j < $jCount; $j++) {
if ($grid[$i][$j] === '1') {
$islandCount++;
dfs($grid, $i, $j);
}
}
}
return $islandCount;
}
function dfs(array &$grid, int $i, int $j): void {
$iLength = count($grid);
$jLength = count($grid[0] ?? []);
if ($i < 0 || $j < 0 || $i >= $iLength || $j >= $jLength || $grid[$i][$j] === '0') {
return;
}
$grid[$i][$j] = '0';
dfs($grid, $i - 1, $j);
dfs($grid, $i + 1, $j);
dfs($grid, $i, $j - 1);
dfs($grid, $i, $j + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment