Skip to content

Commit 34245fb

Browse files
committed
Number of Islands
1 parent cda15ac commit 34245fb

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package leetcode.medium;
2+
3+
public class NumberOfIslands {
4+
5+
int numIslands(char[][] grid) {
6+
if (grid == null || grid.length == 0 || grid[0].length == 0) {
7+
return 0;
8+
}
9+
10+
int count = 0;
11+
12+
for (int i = 0; i < grid.length; i++)
13+
for (int j = 0; j < grid[0].length; j++)
14+
if (grid[i][j] == '1') {
15+
dfs(grid, i, j);
16+
count++;
17+
}
18+
19+
return count;
20+
}
21+
22+
private void dfs(char[][] grid, int i, int j) {
23+
if (i < 0 || i >= grid.length
24+
|| j < 0 || j >= grid[0].length
25+
|| grid[i][j] == '0') {
26+
return;
27+
}
28+
29+
grid[i][j] = '0'; // Mark the cell as visited
30+
31+
// Explore all four directions
32+
dfs(grid, i + 1, j);
33+
dfs(grid, i - 1, j);
34+
dfs(grid, i, j + 1);
35+
dfs(grid, i, j - 1);
36+
}
37+
38+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class NumberOfIslandsTest {
8+
9+
private final NumberOfIslands numberOfIslands;
10+
11+
NumberOfIslandsTest() {
12+
numberOfIslands = new NumberOfIslands();
13+
}
14+
15+
@Test
16+
void testNumIslands1() {
17+
char[][] grid = {
18+
{'1', '1', '0', '0', '0'},
19+
{'1', '1', '0', '0', '0'},
20+
{'0', '0', '1', '0', '0'},
21+
{'0', '0', '0', '1', '1'}
22+
};
23+
assertEquals(3, numberOfIslands.numIslands(grid));
24+
}
25+
26+
@Test
27+
void testNumIslands2() {
28+
char[][] grid = {
29+
{'1', '1', '1', '1', '0'},
30+
{'1', '1', '0', '1', '0'},
31+
{'1', '1', '0', '0', '0'},
32+
{'0', '0', '0', '0', '0'}
33+
};
34+
assertEquals(1, numberOfIslands.numIslands(grid));
35+
}
36+
37+
@Test
38+
void testNumIslands3() {
39+
char[][] grid = {
40+
{'1'}
41+
};
42+
assertEquals(1, numberOfIslands.numIslands(grid));
43+
}
44+
45+
@Test
46+
void testNumIslands4() {
47+
char[][] grid = {
48+
{'0', '0', '0'},
49+
{'0', '0', '0'},
50+
{'0', '0', '0'}
51+
};
52+
assertEquals(0, numberOfIslands.numIslands(grid));
53+
}
54+
55+
@Test
56+
void testNumIslands5() {
57+
char[][] grid = {
58+
{'1', '0', '1', '0'},
59+
{'0', '1', '0', '1'},
60+
{'1', '0', '1', '0'}
61+
};
62+
assertEquals(6, numberOfIslands.numIslands(grid));
63+
}
64+
}

0 commit comments

Comments
 (0)