-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathBFSGrid.java
More file actions
59 lines (52 loc) · 1.76 KB
/
BFSGrid.java
File metadata and controls
59 lines (52 loc) · 1.76 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.LinkedList;
class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class Solution {
// 4 directions
private static int[] dx = new int[] { 1, -1, 0, 0 };
private static int[] dy = new int[] { 0, 0, 1, -1 };
private boolean isValid(boolean[][] vis, int x, int y, int rows, int cols) {
return x >= 0 && y >= 0 && x <= rows - 1 && y <= cols - 1 && !vis[x][y];
}
// Time: O(grid_size), Space: O(grid_size)
public int numConnectedComponent(char[][] grid) {
if (grid == null) {
return 0;
}
int rows = grid.length;
int cols = grid[0].length;
boolean vis[][] = new boolean[rows][cols];
int regions = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (!vis[row][col] && grid[row][col] == '1') {
regions++;
fillSegment(vis, grid, row, col, rows, cols);
}
}
}
return regions;
}
// BFS
private void fillSegment(boolean[][] vis, char[][] grid, int row, int col, int rows, int cols) {
LinkedList<Pair> queue = new LinkedList<>();
queue.add(new Pair(row, col));
vis[row][col] = true;
while (!queue.isEmpty()) {
Pair node = (Pair) queue.removeFirst();
for (int dir = 0; dir < 4; dir++) {
int nextX = node.x + dx[dir];
int nextY = node.y + dy[dir];
if (isValid(vis, nextX, nextY, rows, cols) && grid[nextX][nextY] == '1') {
vis[nextX][nextY] = true;
queue.add(new Pair(nextX, nextY));
}
}
}
}
}