洛谷[https://www.luogu.org/problemnew/show/P1141]
用广度优先搜索会超时两个数据点
//还是会超时,欸,还得优化
#include <bits/stdc++.h>
using namespace std;
#define MAX 1005
struct node{
int x, y;
}s, e;
int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char A[MAX][MAX];
int B[MAX][MAX];
bool visited[MAX][MAX] = {0}; //总的棋盘
queue<struct node> Q;
int BFS(int x, int y, int n) {
if(visited[x][y])
return B[x][y];
while(!Q.empty()) Q.pop();
int ct = 0, i, j;
bool v[MAX][MAX] = {0};
s.x = x;
s.y = y;
Q.push(s);
visited[s.x][s.y] = 1;
v[s.x][s.y] = 1;
ct++;
while(!Q.empty()) {
s = Q.front();
Q.pop();
for(int i = 0; i < 4; i++) {
e.x = s.x + dir[i][0];
e.y = s.y + dir[i][1];
if(v[e.x][e.y] || e.x < 0 || e.y < 0 || e.x >= n || e.y >= n) continue;
if(A[s.x][s.y] == '0') {
if(A[e.x][e.y] == '1'){
visited[e.x][e.y] = 1;
v[e.x][e.y] = 1;
Q.push(e);
ct++;
}
}
else {
if(A[e.x][e.y] == '0') {
visited[e.x][e.y] = 1;
v[e.x][e.y] = 1;
Q.push(e);
ct++;
}
}
}
}
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(v[i][j])
B[i][j] = ct;
}
}
return ct;
}
int main() {
int n, m, i, ct, x, y;
scanf("%d%d", &n, &m);
getchar();
for(i = 0; i < n; i++) {
scanf("%s", A[i]);
}
memset(B, -1, sizeof(B));
for(i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
ct = BFS(x-1, y-1, n);
printf("%d\n", ct);
}
return 0;
}
换成深度优先搜索,求联通块
//求联通块的问题 ,用DFS试一下
#include <bits/stdc++.h>
using namespace std;
#define MAX 1005
int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char A[MAX][MAX];
int B[MAX][MAX];
int xy[1000005][2];
bool v[MAX][MAX] = {0}; //总的棋盘
int n, ct;
void DFS(int x, int y) {
int nx, ny;
xy[ct][0] = x;
xy[ct][1] = y;
ct++;
v[x][y] = 1;
for(int i = 0; i < 4; i++) {
nx = x + dir[i][0];
ny = y + dir[i][1];
if(nx < 0 || ny < 0 || nx >= n || ny >= n || v[nx][ny])
continue;
if(A[x][y] != A[nx][ny])
DFS(x+dir[i][0], y+dir[i][1]);
}
}
int main() {
int m, i, x, y, j;
scanf("%d%d", &n, &m);
getchar();
for(i = 0; i < n; i++) {
scanf("%s", A[i]);
}
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(!v[i][j]) {
ct = 0;
DFS(i, j);
for(int k = 0; k < ct; k++) B[xy[k][0]][xy[k][1]] = ct;
}
}
}
for(i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
printf("%d\n", B[x-1][y-1]);
}
return 0;
}