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:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
分析
这道题是一道很典型的递归题。我们计算island的个数,说到底其实就是计算一个island的最大能够蔓延多大,一旦我们遇到一个’1‘,就标志着遇到了一个新的island,在+1之后,我们需要把这个island蔓延的区域全部击沉(置’0‘),以免在之后的计算中重复计数。
Code
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if (row == 0)
return 0;
int sum = 0;
int col = grid[0].size();
for (int i = 0; i < row; i ++)
for (int j = 0; j < col; j ++)
{
if (grid[i][j] == '1')
{
sum ++;
sink(grid, i, j);
}
}
return sum;
}
void sink(vector<vector<char>>& grid, int x, int y)
{
int row = grid.size();
int col = grid[0].size();
if (x < 0 || x >= row || y < 0 || y >= col)
return;
if (grid[x][y] == '0')
return;
grid[x][y] = '0';
sink(grid, x - 1, y);
sink(grid, x+1, y);
sink(grid, x, y-1);
sink(grid, x, y+1);
return;
}
};
运行效率
Runtime: 16 ms, faster than 98.78% of C++ online submissions for Number of Islands.
Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions forNumber of Islands.