P1141 01迷宫
01迷宫
题意:对于n*n的01矩阵,每次行动只能走到相邻的与当前格点不同的格点上,即若当前为0,则可以走到相邻的1上。有m次提问,输出对应位置(x,y)能到达的最多格点。
思路:(bfs+记忆化+连通块染色)
一开始打了一个比较蠢的记忆化,用f[i][j]储存i,j点的答案,如果重复提问同一点就可以直接输出答案,这样可以拿70分(雾)
然后又想到对于一个点而言,能到达这个点的点答案一定与它相等,于是想到连通块染色,对于每一种连通块,答案是确定的,记录一下即可ac。
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
//Mystery_Sky
//
#define M 1000010
#define INF 0x3f3f3f3f
#define ll long long
inline int read()
{
int x=0, f=1;
char c = getchar();
while(c < '0' || c >'9') {if(c=='-') f=-1; c=getchar();}
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c=getchar();}
return x*f;
}
struct node{
int x, y;
int sit;
};
int n, m;
int map[1001][1001], vis[1001][1001], f[1001][1001];
int Ans[M];
queue <node> Q;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
inline void bfs(int x, int y, int s, int sum)
{
while(!Q.empty()) Q.pop();
vis[x][y] = 1;
Q.push((node){x, y, s});
int ans = 0;
while(!Q.empty()) {
node top = Q.front();Q.pop();
ans++;
for(int i = 0; i < 4; i++) {
int nx = top.x + dx[i];
int ny = top.y + dy[i];
if(nx <= 0 || nx > n || ny <= 0 || ny > n || vis[nx][ny]) continue;
if(map[nx][ny] == map[top.x][top.y]) continue;
vis[nx][ny] = 1;
Q.push((node) {nx, ny, map[nx][ny]});
}
map[top.x][top.y] = sum;
}
Ans[sum] = ans;
return;
}
int main() {
n = read(), m = read();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
scanf("%1d", &map[i][j]);
}
}
int sum = 1;
for(int i = 1; i <= m; i++) {
int x, y;
x = read(), y = read();
if(Ans[map[x][y]] == 0) bfs(x, y, map[x][y], ++sum);
printf("%d\n", Ans[map[x][y]]);
}
return 0;
}
唯愿,青春不辜负梦想,未来星辰闪耀