-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBacktracking.php
75 lines (62 loc) · 1.64 KB
/
Backtracking.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
class Solution {
/**
* grid matrix
*/
private $grid;
/**
* rows
*/
private $rows = 0;
/**
* columns
*/
private $columns = 0;
/**
* visited hash set
*/
private $visited ;
/**
* @param String[][] $grid
* @return Integer
*/
function numIslands($grid) {
$this->grid = $grid;
$this->rows = count($grid);
$this->columns = count($grid[0]);
$this->visited = [];
$islands = 0;
// going to all positions and check the first letter and the walk recursive
for($row = 0; $row < $this->rows; $row++){
for($column = 0; $column < $this->columns; $column++){
if($this->grid[$row][$column] == 1 && !isset($this->visited["$row-$column"])){
$islands++ ;
$this->markLands($row, $column);
}
}
}
return $islands;
}
/**
* @param Integer $row row
* @param Integer $column column
* @return Boolean
*/
function markLands($row, $column) {
// conditions to skip the row and column
if(
isset($this->visited["$row-$column"]) ||
$row > $this->rows || $row < 0 ||
$column > $this->columns || $columns < 0 ||
$this->grid[$row][$column] == 0
) {
return;
}
$this->visited["$row-$column"] = true ;
// mark edges
$this->markLands($row + 1, $column);
$this->markLands($row - 1, $column);
$this->markLands($row, $column + 1);
$this->markLands($row, $column - 1);
}
}