[BFS] FZU 2150

来源:互联网 发布:淘宝购物车怎么扩容 编辑:程序博客网 时间:2024/06/12 23:09

双入口的bfs

数据量比较小,可以暴力枚举

烧完之后找到时间最长的点


#include <cstdlib>#include <cstring>#include <iostream>#include <queue>#define N 20using namespace std;int mintime[ N ][ N ];int visit[ N ][ N ];char map[ N ][ N ];int dirx[ 4 ] = {1, -1, 0, 0};int diry[ 4 ] = {0, 0, 1, -1};int n, m;bool path ( int x, int y ) {        if ( x >= 0 && x < n && y >= 0 && y < m && map[ x ][ y ] == '#' )                return true;        return false;}struct Node {        int x, y;        int cnt;} cur, nex;int bfs ( int x1, int y1, int x2, int y2 ) {        Node n1, n2;        n1.x = x1, n1.y = y1, n1.cnt = 0;        n2.x = x2, n2.y = y2, n2.cnt = 0;        // mintime初始化为inf        memset ( mintime, 0x7f, sizeof ( mintime ) );        memset ( visit, false, sizeof ( visit ) );        mintime[ x1 ][ y1 ] = 0;        mintime[ x2 ][ y2 ] = 0;        queue<Node> q;        q.push ( n1 );        q.push ( n2 );        int ans = -1;        while ( !q.empty () ) {                cur = q.front ();                q.pop ();                for ( int i = 0; i < 4; ++i ) {                        nex.x = cur.x + dirx[ i ];                        nex.y = cur.y + diry[ i ];                        nex.cnt = cur.cnt + 1;                        if ( path ( nex.x, nex.y ) && nex.cnt < mintime[ nex.x ][ nex.y ] ) {                                mintime[ nex.x ][ nex.y ] = nex.cnt;                                q.push ( nex );                        }                }        }        //找到所有#里最大的,如果有剩余刚好是inf        for ( int i = 0; i < n; ++i )                for ( int j = 0; j < m; ++j )                        if ( map[ i ][ j ] == '#' )                                ans = max ( ans, mintime[ i ][ j ] );        return ans;}int main () {        int num;        cin >> num;        for ( int cs = 1; cs <= num; cs++ ) {                cin >> n >> m;                for ( int i = 0; i < n; ++i )                        cin >> map[ i ];                int ans = 0x3f3f3f;                //暴力搜索                for ( int i = 0; i < n; ++i )                        for ( int j = 0; j < m; ++j )                                if ( map[ i ][ j ] == '#' ) //找到第一个#                                        for ( int ii = 0; ii < n; ++ii )                                                for ( int jj = 0; jj < m; ++jj )                                                        if ( map[ ii ][ jj ] ==                                                             '#' ) { //找到第二个#                                                                int tmp = bfs ( i, j, ii, jj );                                                                ans = min ( ans, tmp );                                                        }                if ( ans == 0x3f3f3f )                        ans = -1;                cout << "Case " << cs << ": " << ans << endl;        }        return 0;}


原创粉丝点击