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;
}

转载于:https://www.cnblogs.com/Benjamin-cpp/p/11313082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值