您的位置:首页 > 其它

LeetCode 200 Number of Islands(DFS)

2017-04-09 10:12 351 查看
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
题目大意:给出一个由0和1组成的二维字符数组,1代表陆地,0代表海洋,陆地被海洋分割成很多小岛。求海岛的个数。

解题思路:DFS

代码如下:

int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};

void dfs(char** grid, int gridRowSize, int gridColSize, int x, int y)
{
grid[x][y] = '0';
for(int i = 0;i < 4;i++){
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(nx < 0 || nx >= gridRowSize || ny < 0 || ny >= gridColSize || grid[nx][ny] == '0')
continue;
dfs(grid, gridRowSize, gridColSize, nx, ny);
}
return ;
}

int numIslands(char** grid, int gridRowSize, int gridColSize) {
int ans = 0;
for(int i = 0;i < gridRowSize;i++){
for(int j = 0;j < gridColSize;j++){
if(grid[i][j] == '1')
dfs(grid, gridRowSize, gridColSize, i, j),ans++;
}
}
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode