We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 4554647 commit cd5c7aeCopy full SHA for cd5c7ae
number-of-islands/TonyKim9401.java
@@ -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