社区讨论

70分TLE求调

P114101迷宫参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@mhjuqx5o
此快照首次捕获于
2025/11/04 08:50
4 个月前
此快照最后确认于
2025/11/04 08:50
4 个月前
查看原帖
CPP
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n, m;
string map[1005];
bool vis[1005][1005];
bool in(int x, int y) {
	return x >= 1 && x <= n && y >= 1 && y <= n;
}
struct node {
	int x, y, step;
};
int bfs(int x, int y) {
	int cnt = 1;
	queue<node> q;
	vis[x][y] = true;
	q.push({x, y, 1});
	const int next[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
	while (!q.empty()) {
		node now = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int tx = now.x + next[i][0];
			int ty = now.y + next[i][1];
			if (!vis[tx][ty] && in(tx, ty) && map[now.x][now.y] != map[tx][ty]) {
				vis[tx][ty] = true;
				cnt++;
				q.push({tx, ty, now.step + 1});
			}
		}
	}
	return cnt;
}
int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		cin >> map[i];
		map[i].insert(0, " ");
	}
	while (m--) {
		int x, y;
		cin >> x >> y;
		cout << bfs(x, y) << endl;
		memset(vis, false, sizeof vis);
	}
	return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...