岛屿数量(dfs、bfs实现)

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例 1:

输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1


示例 2:

输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/queue-stack/kbcqv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

dfs方法 

#include 
using namespace std;
int n,m; //行、列
char cc[1001][1001];
void dfs(int i,int j) {
	if(i<0||i>=n||j<0||j>=m||cc[i][j] == '0'){
		return;
	}
	if(cc[i][j] == '1') {
		cc[i][j] = '0';
	}
	dfs(i+1,j);
	dfs(i-1,j);
	dfs(i,j+1);
	dfs(i,j-1);
}
int result(){
	int cnt = 0;
	for(int i=0;i> cc[i][j];
		}
		getchar();
	}
	for(int i=0;i> n >> m;
	cout << result();
	return 0;
}

//bfs方法

 
#include 
#include 
using namespace std;
int n,m;
char cc[1001][1001];

void bfs(int i,int j) {
	cc[i][j] = 0;
	deque queue;
	int code = i*m + j;
	queue.push_back(code);
	while(!queue.empty()) {
		code = queue.front();
		queue.pop_front();
		int k = code/m;
		int l = code%m;
		if(k>0 && cc[k-1][l] == '1') {
			cc[k-1][l] = '0';
			queue.push_back((k-1)*m+l);
		}
		if(k0 && cc[k][l-1] == '1') {
			cc[k][l-1] = '0';
			queue.push_back(k*m+(l-1));
		}
		if(l> cc[i][j];
		}
		getchar();
	}
	
	for(int i=0;i> n >> m;
	cout << result();
	return 0;
}

你可能感兴趣的:(c++,leetcode,广度优先,深度优先)