我们可以使用dfs,走格查找
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, ct;
char c;
int a[1009][1009];
int vis[1009][1009];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
void f (int x, int y) {
vis[x][y] = false;
int nx, ny;
for (int i = 0; i < 4; i++) {
nx = dx[i] + x;
ny = dy[i] + y;
if (nx < 1 || nx > n || ny < 1 || ny > n || a[nx][ny] == a[x][y] || !(vis[nx][ny])) continue;
ct++;
f (nx, ny);
vis[nx][ny] = false;
}
return;
}
int main () {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int k = 1; k <= n; k++) {
cin >> c;
a[i][k] = c - '0';
}
for (int i = 1; i <= m; i++) {
memset (vis, true, sizeof (vis));
cin >> x >> y;
vis[x][y] = false;
ct = 1;
f (x, y);
cout << ct << endl;
}
return 0;
}
结果发现60分,TLE
因为dfs需要递归,
太慢了
所以使用bfs
bfs使用queue代替了慢慢的递归
#include <bits/stdc++.h>
using namespace std;
char c;
int n, m, nextColor;
int a[1009][1009], vis[1009][1009], colorCount[1000009];
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
int bfs (int x, int y) {
if (vis[x][y] != -1)
return colorCount[vis[x][y]];
int cnt = 1;
queue<int> q;
vis[x][y] = nextColor; q.push(x); q.push(y);
while (!q.empty()) {
x = q.front(); q.pop(); y = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 1 || nx > n || ny < 1 || ny > n) continue;
if (vis[nx][ny] == -1 && a[nx][ny] != a[x][y]) {
vis[nx][ny] = nextColor; cnt++;
q.push(nx); q.push(ny);
}
}
}
colorCount[nextColor] = cnt; nextColor++;
return cnt;
}
int main () {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> c;
a[i][j] = c - '0';
}
nextColor = 0;
memset (vis, -1, sizeof(vis));
while (m--) {
int x, y; cin >> x >> y;
cout << bfs(x, y) << endl;
}
return 0;
}