题目描述
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.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析
dfs,遍历过的grid如果是’1’,变成其它字符。
代码
static int mx, my;
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
mx = grid.length;
my = grid[0].length;
int rt = 0;
for (int x = 0; x < mx; x++) {
for (int y = 0; y < my; y++) {
if (grid[x][y] != '1') {
continue;
}
rt++;
dfs(grid, x, y);
}
}
return rt;
}
static void dfs(char[][] grid, int x, int y) {
if (x < 0 || x >= mx || y < 0 || y >= my) {
return;
}
if (grid[x][y] == '1') {
grid[x][y] = '2';
dfs(grid, x + 1, y);
dfs(grid, x - 1, y);
dfs(grid, x, y + 1);
dfs(grid, x, y - 1);
}
}