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;
}
上一篇:xdoj 1402 XY之说走就走的旅行


下一篇:飞飞侠