Skip to content

Commit 4b069f1

Browse files
authored
Added one problem- Number of Islands (#32)
1 parent 7b5eaf7 commit 4b069f1

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

Java/NumberOfIslands.java

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* Given a 2d grid map of '1's (land) and '0's (water), count the number of
3+
* islands. An island is surrounded by water and is formed by connecting
4+
* adjacent lands horizontally or vertically. You may assume all four edges of
5+
* the grid are all surrounded by water.
6+
*
7+
* Problem: https://leetcode.com/problems/number-of-islands/submissions/
8+
*
9+
* Submission link: https://leetcode.com/submissions/detail/385691397/
10+
*
11+
* Runtime: 1 ms, faster than 99.94% of Java online submissions
12+
*
13+
* Memory Usage: 42.3 MB, less than 52.50% of Java online submissions
14+
*
15+
* @author Mirzafazulur Rahamanbaig
16+
*
17+
*/
18+
class NumberOfIslands {
19+
20+
boolean[][] visited;
21+
int r, c;
22+
int islands;
23+
24+
/**
25+
*
26+
* @param grid
27+
* @return
28+
*/
29+
public int numIslands(char[][] grid) {
30+
31+
if (grid == null || grid.length == 0) {
32+
33+
return 0;
34+
}
35+
36+
r = grid.length;
37+
c = grid[0].length;
38+
islands = 0;
39+
visited = new boolean[r][c];
40+
41+
for (int i = 0; i < r; i++) {
42+
43+
for (int j = 0; j < c; j++) {
44+
45+
if (grid[i][j] == '1' && !visited[i][j]) {
46+
47+
_numIslands(grid, i, j);
48+
islands++;
49+
}
50+
}
51+
}
52+
53+
return islands;
54+
}
55+
56+
/**
57+
*
58+
* @param grid
59+
* @param m
60+
* @param n
61+
*/
62+
private void _numIslands(char[][] grid, int m, int n) {
63+
64+
if (m < 0 || m >= r || n < 0 || n >= c || visited[m][n] || grid[m][n] == '0') {
65+
66+
return;
67+
}
68+
69+
visited[m][n] = true;
70+
71+
_numIslands(grid, m + 1, n);
72+
_numIslands(grid, m, n + 1);
73+
_numIslands(grid, m - 1, n);
74+
_numIslands(grid, m, n - 1);
75+
}
76+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
204204
| # | Title | Solution | Time | Space | Difficulty | Tag | Note |
205205
| --- | ----------------------------------------------------------------- | ----------------------------------- | ------ | ------ | ---------- | ---- | ---- |
206206
| 1284 | [Minimum Number of Flips to Convert Binary Matrix to Zero Matrix](https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/) | [C++](./C++/Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix.cpp) | _O(m * n * 2 ^ (m * n))_ | _O(2 ^ (m * n))_ | Hard | BFS | |
207+
| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Java](./Java/NumberOfIslands.java) | O(R * C) | O(R * C) | Medium | BFS |
207208

208209
<br/>
209210
<div align="right">

0 commit comments

Comments
 (0)