-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfIslands.java
More file actions
289 lines (215 loc) · 8.54 KB
/
NumberOfIslands.java
File metadata and controls
289 lines (215 loc) · 8.54 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package Algorithms.Graphs;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 13 Feb 2025
* @link 200. Number of Islands <a href="https://leetcode.com/problems/number-of-islands/">LeetCode link</a>
* @description Islands are connected horizontally or vertically but not diagonally
* @topics Array, Matrix, DFS, BFS, Union Find
* @companies Bloomberg(28), Amazon(14), Uber(11), Microsoft(10), Google(8), LinkedIn(8), Anduril(7), Oracle(6), Apple(5), TikTok(5), Meta(10), Tesla(5), Yandex(5), Snap(5), Samsung(4), Walmart Labs(3), Zoho(3), Nvidia(3), Wells Fargo(3), Capital One(3), Goldman Sachs(23), PayPal(11), Adobe(9), Intel(9), Salesforce(9), Siemens(8), ByteDance(7), Citadel(6), SAP(6), Wix(5)
* NOTE:
* Even though it looks like "Adjacency Matrix Graph"
* but the nodes are not connected properly by edges like it used to connect in Adjacency Matrix
* So, it's not Adjacency Matrix Graph
*/
public class NumberOfIslands {
public static void main(String[] args) {
// char[][] grid = {{1,1,0,0,0},{1,1,0,0,0},{0,0,1,0,0},{0,0,0,1,1}};
/*
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
*/
char[][] grid = {{'1','1','1'},{'0','1','0'},{'1','1','1'}};
System.out.println("numIslands using DFS: " + numIslandsUsingDFS(grid));
grid = new char[][]{{'1','1','1'},{'0','1','0'},{'1','1','1'}};
System.out.println("numIslands using BFS: " + numIslandsUsingBFS(grid));
grid = new char[][]{{'1','1','1'},{'0','1','0'},{'1','1','1'}};
System.out.println("numIslands using Union Find: " + numIslandsUsingUnionFind(grid));
}
public static int numIslandsUsingDFS(char[][] grid) {
int islands = 0;
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[0].length; c++) {
if(grid[r][c] == '1') {
islands++;
dfs(grid, r, c);
}
}
}
return islands;
}
private static void dfs(char[][] grid, int r, int c) {
if(r<0 || r>=grid.length || c<0 || c>=grid[0].length || grid[r][c]=='0') {
return;
}
grid[r][c]='0'; // mark as visited
int[][] dirs = {{1,0}, {0,1}, {-1,0}, {0,-1}}; // {bottom, right, top, left}
for(int[] dir: dirs) {
dfs(grid, r+dir[0], c+dir[1]);
}
}
public static int numIslandsUsingBFS(char[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int islands = 0;
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (grid[r][c] == '1') {
islands++;
grid[r][c] = '0'; // mark as visited
Queue<Integer> queue = new LinkedList<>(); // neighbors
queue.add(r * cols + c); // -> to access row = id/cols; and col = id%cols;... or use int[] {r, c}
while (!queue.isEmpty()) {
int id = queue.remove();
int row = id / cols;
int col = id % cols;
if (row - 1 >= 0 && grid[row - 1][col] == '1') { // topNeighbor
queue.add((row - 1) * cols + col);
grid[row - 1][col] = '0';
}
if (row + 1 < rows && grid[row + 1][col] == '1') { // downNeighbor
queue.add((row + 1) * cols + col);
grid[row + 1][col] = '0';
}
if (col - 1 >= 0 && grid[row][col - 1] == '1') { // leftNeighbor
queue.add(row * cols + col - 1);
grid[row][col - 1] = '0';
}
if (col + 1 < cols && grid[row][col + 1] == '1') { // rightNeighbor
queue.add(row * cols + col + 1);
grid[row][col + 1] = '0';
}
}
}
}
}
return islands;
}
public static int numIslandsUsingBFS2(char[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int islands = 0;
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (grid[r][c] == '1') {
islands++;
bfs(grid, r, c);
}
}
}
return islands;
}
private static void bfs(char[][]grid, int row, int col) {
int rows = grid.length, cols = grid[0].length;
Queue<Integer> q = new LinkedList<>();
q.add(row*cols+col);
grid[row][col] = '0';
int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
while(!q.isEmpty()) {
int num = q.poll();
int r = num / cols, c = num % cols;
for (int[] dir: dirs) {
int nr = r + dir[0], nc = c + dir[1];
if (nr >= rows || nc >= cols || nr < 0 || nc < 0 || grid[nr][nc] != '1') continue;
q.add(nr*cols + nc);
grid[nr][nc] = '0';
}
}
}
public static int numIslandsUsingUnionFind(char[][] grid) { // Disjoint Sets Union DSU
int rows = grid.length;
int cols = grid[0].length;
UnionFind uf = new UnionFind(grid);
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (grid[r][c] == '1') {
grid[r][c] = '0';
// Add neighbors as children for current cell grid[r][c]
if (r - 1 >= 0 && grid[r - 1][c] == '1') {
uf.union(r * cols + c, (r - 1) * cols + c);
}
if (r + 1 < rows && grid[r + 1][c] == '1') {
uf.union(r * cols + c, (r + 1) * cols + c);
}
if (c - 1 >= 0 && grid[r][c - 1] == '1') {
uf.union(r * cols + c, r * cols + c - 1);
}
if (c + 1 < cols && grid[r][c + 1] == '1') {
uf.union(r * cols + c, r * cols + c + 1);
}
}
}
}
return uf.getCount();
}
static class UnionFind {
int count; // # of connected components
int[] parent;
int[] rank;
public UnionFind(char[][] grid) { // for problem 200
count = 0;
int m = grid.length;
int n = grid[0].length;
parent = new int[m * n];
rank = new int[m * n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
parent[i * n + j] = i * n + j; // self as parent
count++;
}
rank[i * n + j] = 0;
}
}
}
public int find(int i) {
if (parent[i] != i) parent[i] = find(parent[i]); // path compression
return parent[i];
}
public void union(int x, int y) { // union with rank
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX] += 1;
}
--count;
}
}
public int getCount() {
return count;
}
}
/**
* this is unused --> just for understanding
*/
@SuppressWarnings("unused")
private static boolean isSameIsland(int m, int n, int[][] grid) {
if (grid[m][n] != 1) return false;
boolean isTrue = false;
// left n-1
if ((n-1)>=0 && grid[m][n-1]==1)
isTrue = true;
// right n+1
if (!isTrue && (n+1) < grid[0].length && grid[m][n+1]==1)
isTrue = true;
// bottom m+1
if ( !isTrue && (m+1) < grid.length && grid[m+1][n]==1)
isTrue = true;
// top m-1
if (!isTrue && (m-1)>=0 && grid[m-1][n]==1)
isTrue = true;
// current
if (!isTrue && grid[m][n] == 1)
isTrue = true;
return isTrue;
}
}