p1141 01迷宫
题目描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190730215337628.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDM3NTcyMw==,size_16,color_FFFFFF,t_70)
代码
#include<bits/stdc++.h>
using namespace std;
int s[1010][1010];
int opt[6][3] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int cou; // 用来存储当前染色到了多少个点
int ans[1010][1010];
int n;
int genx[1010][1010];//用来存储父节点
int geny[1010][1010];
int curx, cury; //用来存储当前节点
void dfs(int x, int y){ //染色用的dfs函数
if(x > n || x < 1 || y > n || y < 1) return ; //越界判断
if(ans[x][y] > -1) return ; //判重(此时ans是两用的,既是存储答案用,也可以拿来判重)
cou++;
genx[x][y] = curx;
geny[x][y] = cury; //设置当前点的gen在哪里,方便后面来查找这个点对应的答案
ans[x][y] = 0; //标记一下当前点
for(int i = 0; i < 4; i++){
if(s[x+opt[i][0]][y+opt[i][1]] != s[x][y])
dfs(x+opt[i][0], y+opt[i][1]);
}
}
int main(){
memset(ans, -1, sizeof(ans)); //初始化成-1,方便后面判重(后面设为0来判重)
memset(genx, 0, sizeof(genx));
memset(geny, 0, sizeof(geny));
int m;
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){ //读入
char str[1010];
scanf("%s", &str);
for(int j = 1; j <= n; j++){
s[i][j] = str[j-1] - 48;
}
}
for(int i = 1; i <= m; i++){
int x, y;
cou = 0;
scanf("%d %d", &x, &y);
if(ans[genx[x][y]][geny[x][y]] > 0){ // 判断当前点是不是以前搜索过的
printf("%d\n", ans[genx[x][y]][geny[x][y]]);
continue;
}
curx = x;
cury = y;
dfs(x, y); //染色
printf("%d\n", cou);
ans[x][y] = cou; //把自己的gen也设成自己,否则如果后面问同一个点输就错了
genx[x][y] = x;
geny[x][y] = y;
}
}