-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.php
44 lines (33 loc) · 992 Bytes
/
solution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
class Solution {
/**
* @param String[][] $grid
* @return Integer
*/
function numIslands($grid) {
// loop through the grid to start from new island.
// mark each node as visited.
// dfs each start go to its 4 directions.
// if all directions are 0s, increase islands counter
$total = 0;
for($i=0; $i<count($grid); $i++){
for($j=0; $j<count($grid[0]); $j++){
if($grid[$i][$j] == 1){
$this->DFS($grid, $i, $j, $total);
$total++;
}
}
}
return $total;
}
function DFS(&$grid, $i, $j, &$total){
if(!isset($grid[$i][$j]) || $grid[$i][$j] == 0){
return;
}
$grid[$i][$j] = 0;
$this->DFS($grid, $i, $j+1, $total);
$this->DFS($grid, $i+1, $j, $total);
$this->DFS($grid, $i, $j-1, $total);
$this->DFS($grid, $i-1, $j, $total);
}
}