算法笔记8.2.1

提示:
#include<iostream>
#include<queue>
using namespace std;
#define maxn 100
struct nod
{
	int x, y;
}node;
int n, m;
int a[maxn][maxn];
bool inq[maxn][maxn] = { false };
queue<nod>q;
int X[] = { 0,0,1,-1 };
int Y[] = { 1,-1,0,0 };
bool judge(int x,int y)
{
	if (a[x][y] == 0 || inq[x][y] == true)return false;
	if (x >= n || x < 0 || y >= n || y < 0 )
		return false;
	return true;
}
void BFS(int x, int y)
{
	node.x = x;
	node.y = y;
	q.push(node);
	inq[node.x][node.y] = true;
	int nowx, nowy;
	while (!q.empty())
	{
		nod temp = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			nowx = temp.x + X[i];
			nowy = temp.y + Y[i];
			if (judge(nowx, nowy))
			{
				node.x = nowx;
				node.y = nowy;
				inq[nowx][nowy] = true;
				q.push(node);
			}
		}
	}
}
int main()
{
	FILE* streaml;
	freopen_s(&streaml, "input.txt", "r", stdin);
	cin >> n >> m;
	int ans = 0;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> a[i][j];
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (a[i][j] == 1&&inq[i][j]==false)
			{
				ans++;
				BFS(i, j);
			}
		}
	}
	cout << ans << endl;
	return 0;
}


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务