Number of islands--Dfs

/*Give you a two-dimensional grid composed of ?'1' (land) and '0' (water), please count the number of islands in the grid.

Islands are always surrounded by water, and each island can only be formed by connecting adjacent land in the horizontal or vertical direction.

In addition, you can assume that all four sides of the grid are surrounded by water.

?

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-islands
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source. */

/*Example 1:

Input:
[
['1','1','1','1','0'],
['1','1','0','1','0'],
['1 ','1','0','0','0'],
['0','0','0','0','0']
]
output: ?1
example?2:

Input:
[
['1','1','0','0','0'],
['1','1','0','0','0'],
['0 ','0','1','0','0'],
['0','0','0','1','1']
]
Output: 3
Explanation: Only for each island It can be connected by adjacent land in the horizontal and/or vertical direction.

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-islands
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source. */

class Solution {
    
    
public:
	void Dfs(vector<vector<char>>& grid, int r, int c) {
    
    
		int row = grid.size();
		int col = grid[0].size();
		//防止重复搜索
		grid[r][c] = '0';
		//上下左右
		if (r + 1 < row && grid[r + 1][c] == '1')
			Dfs(grid, r + 1, c);
		if (r - 1 >= 0 && grid[r - 1][c] == '1')
			Dfs(grid, r - 1, c);
		if (c + 1 < col && grid[r][c + 1] == '1')
			Dfs(grid, r, c + 1);
		if (c - 1 >= 0 && grid[r][c - 1] == '1')
			Dfs(grid, r, c - 1);
	}
	int numIslands(vector<vector<char>>& grid) {
    
    
		if (grid.empty())
			return 0;
		int nums = 0;
		for (int i = 0; i < grid.size(); ++i) {
    
    
			for (int j = 0; j < grid[0].size(); ++j) {
    
    
				if (grid[i][j] == '1') {
    
    
					//每搜索一次就是一块封闭的区域,即一个岛,所以经过一个岛就将岛屿改为水域,
					//最后搜索了几次,就有几个岛
					++nums;
					Dfs(grid, i, j);
				}
			}
		}
		return nums;
	}
};

Guess you like

Origin blog.csdn.net/weixin_45295598/article/details/108911435