FZU_2150_(BFS)

FZU 2150

  • 题意:随便两个出发点,用最短时间遍历所有草地,不能遍历所有草地输出-1,可以遍历则输出最短时间,
  • 4层循环枚举所有出发点,更新最短时间,
#include <iostream>
#include <string.h>
#include <queue>

using namespace std;

int next1[4][2] = {0,1,1,0,0,-1,-1,0};
char grid[11][11];
bool vis[11][11];
int n,m;
int cnt;
struct node {
    int x,y;
    int step;
    node(){}
    node(int a,int b,int c) {
        x = a; y = b; step = c;
    }
};

int bfs(int x1,int y1,int x2,int y2) {
    int ans = 0;
    queue<node> que;
    que.push( node(x1,y1,0) );
    que.push( node(x2,y2,0) );
    vis[x1][y1] = 1;
    vis[x2][y2] = 1;

    while ( !que.empty() ) {
        node cur = que.front();
        que.pop();

        for (int i=0; i<4; i++) {
            int tx = cur.x + next1[i][0];
            int ty = cur.y + next1[i][1];
            if (tx<1 || ty<1 || tx>n || ty>m) continue; // 判断边界
            if (grid[tx][ty] == '.') continue;
            if ( !vis[tx][ty] && grid[tx][ty] == '#' ) {
                vis[tx][ty] = 1;
                que.push( node(tx,ty,cur.step+1) );
                if (cur.step + 1 > ans) ans = cur.step+1;
            }

        }
    }
    // 统计一下是否所有的草地走到了
    for (int i=1; i<=n; i++) 
        for (int j=1; j<=m; j++) 
            if (grid[i][j] == '#' && !vis[i][j] ) 
                return -1; 
    return ans;
}


int main() {
//	freopen("a.txt","r",stdin);
    int times;
    cin >> times;
    while (times--) {
        memset(grid,0,sizeof grid);
        int ans = 0x3f3f3f3f;
        cin >> n >> m;
        for (int i=1; i<=n; i++) 
            for (int j=1; j<=m; j++) 
                cin >> grid[i][j];
            
        for (int i=1; i<=n; i++) {
            for (int j=1; j<=m; j++) {
                // 四层循环枚举 所有的起点,起点可以重复
                for (int a=1; a<=n; a++) {
                    for (int b=1; b<=m; b++) {
                        if (grid[i][j] == '#' && grid[a][b] == '#') {
                            memset(vis,0,sizeof vis);
                            int k = bfs(i,j,a,b);
                            if (k == -1) continue;
                            else 
                                if (k < ans) ans = k;
                        }
                    }
                }

            }
        }
        if (ans == 0x3f3f3f3f)
            printf("Case %d: %d\n",++cnt,-1);
        else 
            printf("Case %d: %d\n",++cnt,ans);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值