Last active
November 14, 2020 19:00
-
-
Save doganoo/6a35074b1367ab628219370da6e891ab to your computer and use it in GitHub Desktop.
Leetcode: 200. Number of Islands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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