P1141 01迷宫
题目描述
有一个仅由数字 0 与 1 组成的 n×n 格迷宫。若你位于一格 0 上,那么你可以移动到相邻 4 格中的某一格 1 上,同样若你位于一格 1 上,那么你可以移动到相邻 4 格中的某一格 0 上。
你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。
输入格式
第一行为两个正整数 n,m。
下面 n 行,每行 n 个字符,字符只可能是 0 或者 1,字符之间没有空格。
接下来 m 行,每行两个用空格分隔的正整数 i,j,对应了迷宫中第 i 行第 j 列的一个格子,询问从这一格开始能移动到多少格。
输出格式
m 行,对于每个询问输出相应答案。
输入输出样例
输入 #1
2 2 01 10 1 1 2 2
输出 #1
4 4
看成每个连通块就好了
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;const int N = 1008, mod = 998244353;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};int n, m;
char e[N][N];
bool v[N][N];
int ans[N][N];
int id[N * 100], cnt;bool check(int x, int y, char c) {return x >= 0 && x < n && y >= 0 && y < n && e[x][y] != c && !v[x][y];
}void bfs(int sx, int sy) {cnt++;queue<pii> q;q.push({sx, sy});v[sx][sy] = true;int res = 1;while (q.size()) {auto [x, y] = q.front();q.pop();ans[x][y] = cnt;for (int i = 0; i < 4; i++) {int nx = x + dx[i];int ny = y + dy[i];if (check(nx, ny, e[x][y])) {v[nx][ny] = true;res++;q.push({nx, ny});}}}id[cnt] = res;
}void solve() {cin >> n >> m;for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {cin >> e[i][j];}}while (m--) {int x, y;cin >> x >> y;x--, y--;if (!v[x][y]) bfs(x, y);cout << id[ans[x][y]] << endl;}}signed main() {ios::sync_with_stdio(false);cin.tie(nullptr), cout.tie(nullptr);int T = 1;
// cin >> T;while (T--) solve();return 0;
}