10分求助
查看原帖
10分求助
679557
dark_assassin楼主2023/2/19 18:31

RT

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define N 105
using namespace std;
char a[N][N];
int n, m;
int ans = 0;
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
struct _Node
{
	int x, y;
};
void bfs(int x, int y)
{
	ans++;
	_Node c = { 0,0 };
	c.x = x;
	c.y = y;
	queue<_Node>que;
	que.push(c);
	a[x][y] = '0';//深搜必须标记访问,以免导致死循环
	while (que.size())
	{
		_Node k = que.front();
		que.pop();
		for (int i = 0; i < 4; i++)
		{
			int nx = k.x + dir[i][0];//注意是k.x+dir[i][0]不是x+dir[i][0]
			int ny = k.y + dir[i][1];//和上面同理
			if (nx >= 0 && nx < n && ny >= 1 && ny <= m && a[nx][ny] != '0')
			{
				a[nx][ny] = '0';//标记访问,切莫忘记
				c.x = nx;
				c.y = ny;
				que.push(c);
				//bfs不是递归,不需要调用自身,数据已经保存在队列中了
				//bfs(nx, ny);
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m+1; j++)//get会读入回车键所以要增加一个读入数据
		{
			cin.get(a[i][j]);
		}
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 1; j < m + 1; j++)
		{
			if (a[i][j] != '0')
			{
				bfs(i, j);
				
			}
		}
	}
	cout << ans << endl;
	return 0;
}
2023/2/19 18:31
加载中...