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’组成的矩阵,0代表水,1代表陆地,连起来的1(只能是横竖相连,不能斜着)组成岛,求岛的个数。
解析:首先从第一行第一列开始遍历,找到第一个等于1的元素grid[i,j],将其定义为一个岛,那这个岛能不能向外扩展呢,就要看元素grid[i,j]的上下左右四个元素(我们称之为四邻,当然矩阵边界元素会有四邻不全的情况)是不是也等于1,如果右面的元素grid[i,j+1]也等于1说明岛可以像右扩展,同理判断左上下三个元素,上下左右的四个元素每个又都存在各自的四邻,当所有向外扩展的点都不能继续扩展的时候就找到了一个岛,所以这是一个递归的过程,在递归的同时我们需要有一个标识来标记这个元素是否被访问过,否则的话递归就没有出口了,为了节省存储空间可以改变访问过的元素的值来表示该元素是否被访问,而改变的值我们也可以定义成当前已经找出来的岛的个数。
代码实现:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int count = 0;
for(int i = 0; i<grid.size(); i++)
for(int j = 0; j<grid[0].size(); j++)
if(grid[i][j] == '1') help(grid, i, j, count++);
return count;
}
void help(vector<vector<char>>& grid, int i, int j, int count){
if(i == grid.size() || i < 0 || j == grid[0].size() || j < 0 || grid[i][j] != '1') return;//出口条件:越过了边界或者 //元素值不为1
grid[i][j] = '2' + count;//用当前已经找到的岛的个数重新标记
help(grid, i+1, j, count);
help(grid, i, j+1, count);
help(grid, i-1, j, count);
help(grid, i, j-1, count);
}
};