LeetCode 200 岛屿数量(简单DFS)

 直接用DFS进行搜索即可

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()) {
        	return 0;
        }
        int ans = 0;
        for(int i = 0; i < grid.size(); ++i) {
        	for(int j = 0; j < grid[0].size(); ++j) {
        		if(grid[i][j] == '1') {
        			ans++;
        			DFS(grid, i, j);
        		}
        	}
        }
        return ans;
    }
	void DFS(vector<vector<char>>& grid, int row, int col) {
		if(row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] == '0') {
			return;
		}
		grid[row][col] = '0';
		DFS(grid, row + 1, col);
		DFS(grid, row - 1, col);
		DFS(grid, row, col + 1);
		DFS(grid, row, col - 1);
	}
};
作者:LightAc
出处:https://www.cnblogs.com/lightac/
联系:
Email: dzz@stu.ouc.edu.cn
QQ: 1171613053
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/lightac/p/12738302.html