Skip to content

Commit 7cdd969

Browse files
committed
leetcode 200
1 parent 6f1e8da commit 7cdd969

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Week_03/id_12/LeetCode_200_012.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
2+
//
3+
// Example 1:
4+
//
5+
//
6+
//Input:
7+
//11110
8+
//11010
9+
//11000
10+
//00000
11+
//
12+
//Output: 1
13+
//
14+
//
15+
// Example 2:
16+
//
17+
//
18+
//Input:
19+
//11000
20+
//11000
21+
//00100
22+
//00011
23+
//
24+
//Output: 3
25+
//
26+
27+
28+
class Solution {
29+
30+
int[] x = {1, 0, -1, 0};
31+
int[] y = {0, -1, 0, 1};
32+
33+
public int numIslands(char[][] grid) {
34+
int count = 0;
35+
for (int i = 0; i < grid.length; i++) {
36+
for (int j = 0; j < grid[i].length; j++) {
37+
if (grid[i][j] == '1') {
38+
count++;
39+
sink(grid, i, j);
40+
}
41+
}
42+
}
43+
return count;
44+
}
45+
46+
private void sink(char[][] grid, int i, int j) {
47+
if (i < 0 || j < 0 || i > grid.length - 1 || j > grid[i].length - 1 || grid[i][j] == '0') {
48+
return;
49+
}
50+
grid[i][j] = '0';
51+
for (int index = 0; index < 4; index++) {
52+
sink(grid, i + x[index], j + y[index]);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)