Skip to content

Commit b86db97

Browse files
committed
Add Solution.java for 0200.Number of lslands
1 parent 7e4f047 commit b86db97

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Number of Islands
2+
3+
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.
4+
5+
6+
## Example 1:
7+
```
8+
Input:
9+
11110
10+
11010
11+
11000
12+
00000
13+
14+
Output: 1
15+
```
16+
17+
## Example 2:
18+
```
19+
Input:
20+
11000
21+
11000
22+
00100
23+
00011
24+
25+
Output: 3
26+
```
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int numIslands(char[][] grid) {
3+
int islandNum = 0;
4+
for (int i = 0; i < grid.length; i++) {
5+
for (int j = 0; j < grid[0].length; j++) {
6+
if (grid[i][j] == '1') {
7+
infect(grid, i, j);
8+
islandNum ++;
9+
}
10+
}
11+
}
12+
return islandNum;
13+
}
14+
15+
public void infect(char[][] grid, int i, int j) {
16+
if (i < 0 || i >= grid.length ||
17+
j < 0 || j >= grid[0].length ||
18+
grid[i][j] != '1') {
19+
return;
20+
}
21+
grid[i][j] = '2';
22+
infect(grid, i + 1, j);
23+
infect(grid, i - 1, j);
24+
infect(grid, i, j + 1);
25+
infect(grid, i, j - 1);
26+
}
27+
}

0 commit comments

Comments
 (0)