DFS解决连通块问题

#include
using namespace std;
char a[50][50];
int book[50][50],m,n;
void dfs(int x, int y, int cnt)
{
	if (x<0 || x>m || y < 0 || y>n)
		return;
	if (book[x][y] > 0 || a[x][y] != '@')
		return;
	a[x][y] = cnt;
	for (int dx = -1; dx <= 1; dx++)
	{
		for (int dy = -1; dy <= 1; dy++)
		{
			if(dx!=0||dy!=0)
				dfs(x+dx,y+dy,cnt);
		}

	}

}
int main()
{
	cin >> m >> n;
	for (int i = 0; i < m; i++)
	{
		scanf("%s", a[i]);
	}
	int cnt = 0;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (book[i][j] == 0 && a[i][j] == '@')
				dfs(i, j, ++cnt);
		}
	}
	return 0;
}

 

你可能感兴趣的:(算法(深度优先搜索))