Skip to content

Commit cd5c7ae

Browse files
committed
Number Of Islands
1 parent 4554647 commit cd5c7ae

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

number-of-islands/TonyKim9401.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// TC: O(n * m)
2+
// retrieve all elemetns, grid.length * grid[0].length
3+
// SC: O(n * m(
4+
// need to change all elements from 1 to 0 in the worst case
5+
class Solution {
6+
int output = 0;
7+
public int numIslands(char[][] grid) {
8+
for (int i = 0; i < grid.length; i++) {
9+
for (int j = 0; j < grid[0].length; j++) {
10+
if (grid[i][j] == '1') {
11+
output += 1;
12+
countIslands(i, j, grid);
13+
}
14+
}
15+
}
16+
return output;
17+
}
18+
19+
private void countIslands(int i, int j, char[][] grid) {
20+
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return;
21+
if (grid[i][j] == '0') return;
22+
grid[i][j] = '0';
23+
countIslands(i+1, j, grid);
24+
countIslands(i-1, j, grid);
25+
countIslands(i, j+1, grid);
26+
countIslands(i, j-1, grid);
27+
}
28+
}

0 commit comments

Comments
 (0)