DFS 和 BFS 都试过了,都是70,7 AC 3 TLE 。
DFS
#include<bits/stdc++.h>
using namespace std;
#define N 1010
bool mp[N][N], vis[N][N];
int ans, n, m, xx, yy;
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 (mp[sx][sy] == !mp[x][y] && sx >= 1 && sx <= n && sy >= 1 && sy <= n && !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 <= m; i++) {
memset(vis, 0, sizeof(vis));
ans = 0;
cin >> xx >> yy;
dfs(xx, yy);
cout << ans << endl;
}
return 0;
}
BFS
#include<bits/stdc++.h>
using namespace std;
#define N 1010
bool mp[N][N], vis[N][N];
int ans, n, m, xx, yy;
int dx[4] = {-1, 0, 0, 1};
int dy[4] = {0, -1, 1, 0};
struct node {
int x, y;
};
queue<node> q;
void bfs() {
q.push(node{xx, yy});
vis[xx][yy] = true;
while (!q.empty()) {
node tmp = q.front();
int x = tmp.x, y = tmp.y;
ans++;
for (int i = 0; i < 4; i++) {
int sx = x + dx[i], sy = y + dy[i];
if (mp[sx][sy] == !mp[x][y] && sx >= 1 && sx <= n && sy >= 1 && sy <= n && !vis[sx][sy]) {
vis[sx][sy] = true;
q.push(node{sx, sy});
}
}
q.pop();
}
}
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 <= m; i++) {
memset(vis, 0, sizeof(vis));
ans = 0;
cin >> xx >> yy;
bfs();
cout << ans << endl;
}
return 0;
}