Number of Islands 岛屿的个数

给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1

示例 2:

输入:
11000
11000
00100
00011

输出: 3

思路:这道题和前几道题一样都是dfs,Surrounded Regions 被围绕的区域Flood Fill 图像渲染,可以先看下这两道题目,都是给定二维数组,把相同色块的变成另外一种颜色的模式,那么这道题其实就是加了一个计数的模块,记录有多少块这样的色块。我们使用一个bool的flag来表示一个色块是否已经被改变过,注意flag的传递方式必须是引用,我们只对色块的起始点做加1操作,并把flag赋值为false,那么在同一个色块递归遍历的时候就不会再+1了。

参考代码:

class Solution {
public:
void numIslandsCore(vector<vector<char>>& grid, int &res,bool &flag,char old,char newC,int row,int col) {
	if (grid[row][col] == old) {
		if (!flag) {
			flag = true;
			res++;
		}
		grid[row][col] = '0';
		if (row > 0) numIslandsCore(grid, res, flag, old, newC, row - 1, col);
		if (row < (grid.size()-1)) numIslandsCore(grid, res, flag, old, newC, row + 1, col);
		if (col > 0) numIslandsCore(grid, res, flag, old, newC, row, col-1);
		if (col < (grid[0].size()-1)) numIslandsCore(grid, res, flag, old, newC, row, col+1);
	}
}
int numIslands(vector<vector<char>>& grid) {
	if (grid.empty()) return 0;
	int res = 0;
	for (int i = 0; i < grid.size(); i++) {
		for (int j = 0; j < grid[0].size(); j++) {
			bool flag = false;
			numIslandsCore(grid, res, flag, '1', '0', i, j);
			flag = false;
		}
	}
	return res;
}
};

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/82748577
今日推荐