求助:队列BFS全部爆
查看原帖
求助:队列BFS全部爆
485139
Dingdong2334楼主2022/8/9 21:15

求助各位大神,队列BFS全部MLE或TLE,无WA或AC。

测试过了代码49行(输出test),一直死循环,不知道为什么,检查不出。

感激不尽!!!

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>

using namespace std;

int n, m;
char a[1001][1001];
int b, c, ans;
int flag[1001][1001];

int xx[] = {-1, 0, 1, 0};
int yy[] = {0, 1, 0, -1};
bool vis[1001][1001];

struct node
{
	int x;
	int y;
	int step;
};

queue <node> q;

void bfs(int d, int f)
{
	memset(vis, 0, sizeof(vis));
	ans = 1;
	vis[d][f] = true;
	while(!q.empty() )
	{
		q.pop() ;
	}
	q.push( (node){d, f, 1} );
	while(!q.empty())
	{
		node top = q.front();
		q.pop();
		for(int i = 0;i < 4;i ++)
		{
			int dx = top.x + xx[i];
			int dy = top.y + yy[i];
//			cout << "---test---" << endl;
			if(dx >= 1 and dx <= n and dy >= 1 and dy <= n and vis[dx][dy] == false)
			{
				if(a[top.x][top.y] != a[dx][dy])
				{
					vis[dx][dy] == true; 
					ans ++;
					q.push( (node){dx, dy, top.step + 1} );
				}
			}
		}
	}
}

int main()
{
	cin >> n >> m;
	for(int i = 1;i <= n;i ++)
	{
		for(int j = 1;j <= n;j ++)
		{
			cin >> a[i][j];
		}
	}
	for(int i = 1;i <= m;i ++)
	{
		cin >> b >> c;
		if(flag[b][c] != 0)
		{
			cout << flag[b][c] << endl;
			continue;
		}
		bfs(b, c);
		flag[b][c] = ans;
		cout << ans << endl;
	}
	return 0;
}
2022/8/9 21:15
加载中...