forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfIslands.java
72 lines (60 loc) · 1.83 KB
/
NumberOfIslands.java
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
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Solution {
/*
* @param grid: a boolean 2D matrix
* @return: an integer
*/
public int numIslands(boolean[][] grid) {
// write your code here
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
int islands = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j]) {
markByBFS(grid, i, j);
islands++;
}
}
}
return islands;
}
private void markByBFS(boolean[][] grid, int x, int y) {
// magic numbers!
int[] directionX = {0, 1, -1, 0};
int[] directionY = {1, 0, 0, -1};
Queue<Coordinate> queue = new LinkedList<>();
queue.offer(new Coordinate(x, y));
grid[x][y] = false;
while (!queue.isEmpty()) {
Coordinate coor = queue.poll();
for (int i = 0; i < 4; i++) {
Coordinate adj = new Coordinate(
coor.x + directionX[i],
coor.y + directionY[i]
);
if (!inBound(adj, grid)) {
continue;
}
if (grid[adj.x][adj.y]) {
grid[adj.x][adj.y] = false;
queue.offer(adj);
}
}
}
}
private boolean inBound(Coordinate coor, boolean[][] grid) {
int n = grid.length;
int m = grid[0].length;
return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m;
}
}