0w1

Yuki 157 2つの空洞 ( 0-1 BFS )

No.157 2つの空洞 - yukicoder
0-1 BFS (いらないけど

#include <bits/stdc++.h>
using namespace std;

const int dx[] = { 0, 1, 0, -1 };
const int dy[] = { 1, 0, -1, 0 };

int in_range( int h, int w, int x, int y ){
  return 0 <= x and x < h and 0 <= y and y < w;
}

signed main(){
  int W, H; cin >> W >> H;
  vector< string > G( H );
  for( int i = 0; i < H; ++i )
    cin >> G[ i ];
  for( int i = 0; i < H; ++i )
    for( int j = 0; j < W; ++j )
      if( G[ i ][ j ] == '.' ){
        queue< pair< int, int > > que;
        vector< vector< int > > vis( H, vector< int >( W ) );
        que.emplace( i, j );
        vis[ i ][ j ] = 1;
        while( not que.empty() ){
          int x, y; tie( x, y ) = que.front(); que.pop();
          for( int di = 0; di < 4; ++di ){
            int nx = x + dx[ di ];
            int ny = y + dy[ di ];
            if( not in_range( H, W, nx, ny ) ) continue;
            if( vis[ nx ][ ny ] ) continue;
            if( G[ nx ][ ny ] == '#' ) continue;
            vis[ nx ][ ny ] = 1;
            que.emplace( nx, ny );
          }
        }
        for( int ni = 0; ni < H; ++ni )
          for( int nj = 0; nj < W; ++nj )
            if( G[ ni ][ nj ] == '.' and not vis[ ni ][ nj ] ){
              deque< tuple< int, int, int > > qued;
              qued.emplace_back( 0, ni, nj );
              vis[ ni ][ nj ] = 2;
              while( not qued.empty() ){
                int d, x, y; tie( d, x, y ) = qued.front(); qued.pop_front();
                for( int di = 0; di < 4; ++di ){
                  int nx = x + dx[ di ];
                  int ny = y + dy[ di ];
                  if( not in_range( H, W, nx, ny ) ) continue;
                  if( vis[ nx ][ ny ] == 2 ) continue;
                  if( vis[ nx ][ ny ] == 1 )
                    cout << d << endl, exit( 0 );
                  vis[ nx ][ ny ] = 2;
                  if( G[ nx ][ ny ] == '.' )
                    qued.emplace_front( d, nx, ny );
                  else
                    qued.emplace_back( d + 1, nx, ny );
                }
              }
            }
      }
  return 0;
}