您的位置:首页 > 其它

[leetcode 200] Number of Islands

2015-12-13 13:14 357 查看
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.

Solution:

dfs遍历一遍,在grid[i][j]如果是1,就把这个位置和周围置成2(任意非1和0的值), 这样遇到的1的个数,即为islands个数

void dfs(char** grid, int m, int n, int i, int j)
{
if (i < 0 || i >= m || j < 0 || j >= n)
return;
if (grid[i][j] == '1')
{
grid[i][j] = '2';
dfs(grid, m, n, i - 1, j);
dfs(grid, m, n, i + 1, j);
dfs(grid, m, n, i, j - 1);
dfs(grid, m, n, i, j + 1);
}
}

int numIslands(char** grid, int gridRowSize, int gridColSize)
{
int count = 0;
int i = 0, j = 0;
if (gridRowSize == 0 || gridColSize == 0 || grid == NULL)
return count;

for (i = 0; i < gridRowSize; i++)
{
for (j = 0; j < gridColSize; j++)
{
if (grid[i][j] != '1')
{
continue;
}
count++;
dfs(grid, gridRowSize, gridColSize, i, j);
}
}

return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: