-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumberOfIslands.java
More file actions
59 lines (48 loc) · 1.69 KB
/
NumberOfIslands.java
File metadata and controls
59 lines (48 loc) · 1.69 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
package graph;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/number-of-islands
* Difficulty: Medium
* Time complexity: O(m * n)
* Space complexity: O(m * n)
*/
public class NumberOfIslands {
private int[][] visited;
private int[][] directions;
public int numIslands(char[][] grid) {
visited = new int[grid.length][grid[0].length];
directions = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int islands = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (visited[i][j] == 0 && grid[i][j] == '1') {
dfs(new int[] {i, j}, grid);
islands++;
}
}
}
return islands;
}
private void dfs(int[] start, char[][] grid) {
Deque<int[]> stack = new LinkedList<>();
stack.push(start);
while (!stack.isEmpty()) {
int[] current = stack.pop();
if (visited[current[0]][current[1]] == 0) {
visited[current[0]][current[1]] = 1;
stack.push(current);
for (int[] dir : directions) {
int x = current[0] + dir[0];
int y = current[1] + dir[1];
if (x >= 0 && y >= 0 && x < grid.length && y < grid[0].length
&& visited[x][y] == 0 && grid[x][y] == '1') {
stack.push(new int[] {x, y});
}
}
} else if (visited[current[0]][current[1]] == 1) {
visited[current[0]][current[1]] = 2;
}
}
}
}