DFS 样例通过,7WA3TLE求助!
#include<bits/stdc++.h>
using namespace std;
#define N 1010
bool mp[N][N], vis[N][N], xx, yy;
int ans, n, m;
int dx[4] = {-1, 0, 0, 1};
int dy[4] = {0, -1, 1, 0};
void dfs(int x, int y) {
ans++;
vis[x][y] = 1;
for (int i = 0; i < 4; i++) {
int sx = x + dx[i], sy = y + dy[i];
if (sx >= 1 && sx <= n && sy >= 1 && sy <= n && mp[sx][sy] != mp[x][y] && !vis[sx][sy]) dfs(sx, sy);
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) {
char c;
cin >> c;
mp[i][j] = c - '0';
}
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) cout << mp[i][j];
for (int i = 1; i <= m; i++) {
memset(vis, 0, sizeof(vis));
ans = 0;
cin >> xx >> yy;
dfs(xx, yy);
cout << ans << endl;
}
return 0;
}