AOJ 0558 Cheese (多次bfs)

和暑假一道多校脸萌的题一样

题意:就是有N个奶酪工厂。每个工厂的奶酪对应1,2,3-N,每次一块奶酪老鼠的体力会加1,他只能吃比小于等于自己体力值的奶酪。初始体力为1。每个工厂只能吃一次。求吃完所有工厂需要最小的步数。

思路:只能按照顺序去吃,所以是多次bfs 即可。

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<map>
#include<set>
#include<algorithm>

using namespace std;
const int MAX = 1010;
char str[MAX][MAX];
bool used[MAX][MAX];
const int xx[] = {1,0,-1,0};
const int yy[] = {0,-1,0,1};
int H,W,N;
class Point{
public:
    int x,y;
    int t;
    Point(int xx=0,int yy = 0,int tt=0){
        x = xx;
        y = yy;
        t = tt;
    }
};
Point now;
bool Check(Point A){
    if(A.x < 0 || A.y < 0 || A.x >= H || A.y >= W)//注意范围
        return false;
    return true;
}
int bfs(Point B,char factory){
    queue<Point> q;
    while(!q.empty())   q.pop();
    q.push(B);
    while(!q.empty()){
        Point v = q.front();q.pop();
        for(int i=0;i<4;++i){
            int tx = v.x + xx[i];
            int ty = v.y + yy[i];
            int tt = v.t + 1;
            if(!Check(Point(tx,ty,tt)) || str[tx][ty] == 'X')
                continue;
            if(str[tx][ty] == factory){
                now = Point(tx,ty,0);//步数要再次初始为0
                return tt;
            }
            if(!used[tx][ty]){
                used[tx][ty] = true;
                q.push(Point(tx,ty,tt));
            }
        }
    }
    return 0;
}
int solve(){
    int res = 0;

    for(int i=1;i<=N;++i){
        memset(used,false,sizeof(used));
        res += bfs(now,i+'0');
    }
    return res;
}
int main(void){
    scanf("%d%d%d",&H,&W,&N);
    for(int i=0;i<H;++i){
        scanf("%s",str[i]);
        for(int j=0;j<W;++j){
            if(str[i][j] == 'S'){
                now = Point(i,j,0);
            }
        }
    }
    printf("%d\n",solve());
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值