forked from algorithm020/algorithm020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumIslands.php
More file actions
43 lines (41 loc) · 1.16 KB
/
numIslands.php
File metadata and controls
43 lines (41 loc) · 1.16 KB
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
<?php
/**
* User: zavier
* Date: 2021/1/3 11:42 下午
* Email: <1262660796@qq.com>
*/
class Solution {
/**
* @param String[][] $grid
* @return Integer
*/
function numIslands($grid) {
$num = 0;
foreach ($grid as $y => &$row) {
foreach ($row as $x => &$cell) {
if ($cell == 1) {
$this->flipIslands($grid, $y, $x);
$num ++;
}
}
}
return $num;
}
function flipIslands(&$grid, $y, $x) {
if (isset($grid[$y][$x]) && $grid[$y][$x] == 1) {
$grid[$y][$x] = 2;
if (isset($grid[$y][$x+1]) && $grid[$y][$x+1] == 1) {
$this->flipIslands($grid, $y, $x+1);
}
if (isset($grid[$y][$x-1]) && $grid[$y][$x-1] == 1) {
$this->flipIslands($grid, $y, $x-1);
}
if (isset($grid[$y+1][$x]) && $grid[$y+1][$x] == 1) {
$this->flipIslands($grid, $y+1, $x);
}
if (isset($grid[$y-1][$x]) && $grid[$y-1][$x] == 1) {
$this->flipIslands($grid, $y-1, $x);
}
}
}
}