AOJ0558(cheese, BFS)

16 篇文章 0 订阅

typical BFS usage:
first use 2 array, one for record map, the other for shortest path/flag visit.

BFS feature:
the shortest path from one to the other, just one point!!!!(单源路)

//#define LOCAL

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

#define SIZE 1010

using namespace std;

char map[SIZE][SIZE];
int dir[][2] = {0, 1, 0, -1, 1, 0, -1, 0};

int bfs(int &x, int &y, int h, int w, int target){
    int step[SIZE][SIZE];
    for(int i = 0; i < h; i++)
        fill(step[i], step[i] + w, -1);
    step[x][y] = 0;

    queue<pair<int, int> > q;
    q.push(make_pair(x, y));

    while(!q.empty()){
        pair<int, int> temp = q.front();
        q.pop();

        if(map[temp.first][temp.second] == target + '0'){
            x = temp.first;
            y = temp.second;
            return step[x][y];
        }

        for(int i = 0; i < 4; i++){
            int newx = temp.first + dir[i][0];
            int newy = temp.second + dir[i][1];

            if(0 <= newx && newx < h && 0 <= newy && newy < w
                && step[newx][newy] == -1 
                && map[newx][newy] != 'X'){
                q.push(make_pair(newx, newy));
                step[newx][newy] = step[temp.first][temp.second] + 1;
            }
        }
    }
}

int main(void){
#ifdef LOCAL
    freopen("data.in", "r", stdin);
#endif
    int n, w, h;
    int x, y;

    scanf("%d%d%d", &h, &w, &n);
    getchar();
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            scanf("%c", &map[i][j]);

            if(map[i][j] == 'S'){
                x = i;
                y = j;
            }
        }
        getchar();
    }

    int result = 0;
    for(int i = 1; i <= n; i++)
        result += bfs(x, y, h, w, i);

    printf("%d\n", result);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值