题目描述
有一个仅由数字0与1组成的n×n格迷宫。若你位于一格0上,那么你可以移动到相邻4格中的某一格1上,同样若你位于一格1上,那么你可以移动到相邻4格中的某一格0上。
你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。
输入格式
第1行为两个正整数n,m。
下面n行,每行n个字符,字符只可能是0或者1,字符之间没有空格。
接下来m行,每行2个用空格分隔的正整数i,j,对应了迷宫中第i行第j列的一个格子,询问从这一格开始能移动到多少格。
输出格式
m行,对于每个询问输出相应答案。
输入
2 2
01
10
1 1
2 2
输出
4
4
#include<bits/stdc++.h>
using namespace std;
#define pi acos(-1)
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define mem(a) memset(a,0,sizeof(a))
#define cio ios::sync_with_stdio(false);
int n, m;
int k = 1;
int s[1010][1010];
int vis[1010][1010];
int cnt[1000010];
int next[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};
void dfs(int xx, int yy)
{
vis[xx][yy] = k; //将该点归入连通块中
for(int i = 0; i < 4; i++){ //往四个方向寻找
int tx = xx+next[i][0];
int ty = yy+next[i][1];
if(tx<1||tx>n||ty<1||ty>n) continue; //判断是否越界
if(vis[tx][ty]==0&&s[tx][ty]!=s[xx][yy]){ //判断是否满足连通块的要求
dfs(tx,ty); //进入下一次连通块判断
}
}
}
int main()
{
cio;
cin >> n >> m;//读入地图大小以及询问次数
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
char a;
cin >> a;
s[i][j] = a-'0'; //读入地图(由于连续用字符读入)
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(vis[i][j]==0){ //如果该点未在连通块中,搜索一个新的连通块
dfs(i,j);
k++; //下一个连通块的标记
}
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cnt[vis[i][j]]++; //统计连通块的大小
}
}
while(m--){
int x1, y1;
cin >> x1 >> y1;
cout << cnt[vis[x1][y1]] << endl; //输出该点所在的连通块的大小
}
return 0;
}
下面是BFS代码TLE样例2和10,有兴趣可以研究一下,我吐了,求大佬拯救
#include<bits/stdc++.h>
using namespace std;
#define pi acos(-1)
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define mem(a) memset(a,0,sizeof(a))
#define cio ios::sync_with_stdio(false);
struct node
{
int x, y;
}q[1000010];
int k = 1;
int n, m;
int s[1010][1010];
int vis[1010][1010];
int cnt[1000010];
int next[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};
void bfs(int xx, int yy)
{
mem(q);
int head = 1;
int tail = 1;
q[tail].x = xx;
q[tail].y = yy;
vis[xx][yy] = k;
cnt[k]++;
tail++;
while(head<tail){
for(int i = 0; i < 4; i++){
int tx = q[head].x+next[i][0];
int ty = q[head].y+next[i][1];
if(tx<0||tx>=n||ty<0||ty>=n) continue;
if(vis[tx][ty]==0&&s[tx][ty]!=s[q[head].x][q[head].y]){
cnt[k]++;
vis[tx][ty] = k;
q[tail].x = tx;
q[tail].y = ty;
tail++;
}
}
head++;
}
}
int main()
{
cio;
cin >> n >> m;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
char a;
cin >> a;
s[i][j] = a-'0';
}
}
while(m--){
int sx,sy;
cin >> sx >> sy;
if(vis[sx-1][sy-1]==0){
bfs(sx-1,sy-1);
cout << cnt[vis[sx-1][sy-1]] << endl;
k++;
}else{
cout << cnt[vis[sx-1][sy-1]] << endl;
}
}
return 0;
}