結果

問題 No.157 2つの空洞
ユーザー motimoti
提出日時 2015-04-15 01:42:57
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,825 bytes
コンパイル時間 777 ms
コンパイル使用メモリ 74,616 KB
実行使用メモリ 529,280 KB
最終ジャッジ日時 2023-09-17 20:20:42
合計ジャッジ時間 4,677 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 2 ms
4,376 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 2 ms
4,376 KB
testcase_12 WA -
testcase_13 WA -
testcase_14 AC 2 ms
4,380 KB
testcase_15 AC 2 ms
4,376 KB
testcase_16 AC 2 ms
4,380 KB
testcase_17 MLE -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <queue>
#include <tuple>
using namespace std;

#define REP(i,a,b) for(int i=a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)

typedef long long ll;

int W, H;
char G[22][22];
int F[22][22];
bool vis[22][22];

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

inline bool valid(int x, int y) {
  return 0<=x&&x<W && 0<=y&&y<H;
}

inline bool balid(int x, int y) {
  return G[y][x] == '.';
}

void bfs(int x, int y, int key) {
  std::queue<std::pair<int, int>> q;
  q.emplace(x, y);
  while(!q.empty()) {
    vis[y][x] = 1;
    F[y][x] = key;
    x = q.front().first, y = q.front().second;
    q.pop();
    rep(k, 4) {
      int nx = x+dx[k], ny = y+dy[k];
      if(!valid(nx, ny) || !balid(nx, ny)) { continue; }
      if(vis[ny][nx]) { continue; }
      q.emplace(nx, ny);
    }
  }
}

int main() {

  cin >> W >> H;
  rep(i, H) rep(j, W) {
    cin >> G[i][j];
  }

  int key = 1;
  rep(i, H) rep(j, W) {
    if(G[i][j] == '.' && F[i][j] == 0) {
      bfs(j, i, key++);
    }
  }

  int sx, sy;
  rep(i, H) rep(j, W) {
    if(F[i][j] == 1) {
      sx = j, sy = i;
      goto ex;
    }
  }
ex:;
  
  int const INF = 1<<29;
  int ans = INF;
  int dist[22][22];
  rep(i, 22) rep(j, 22) dist[i][j] = INF;
  std::priority_queue<std::tuple<int,int,int>> pq;
  pq.emplace(0, sx, sy);
  dist[sy][sx] = 0;
  while(!pq.empty()) {
    int cost = -std::get<0>(pq.top());
    int x = std::get<1>(pq.top());
    int y = std::get<2>(pq.top());
    pq.pop();
    if(F[y][x]==2) {
      ans = dist[y][x];
      break;
    }
    rep(i, 4) {
      int nx = x+dx[i], ny = y+dy[i];
      if(!valid(nx, ny)) { continue; }
      int ncost = cost+int(G[ny][nx]=='#');
      if(dist[ny][nx] <= ncost) { continue; }
      dist[ny][nx] = ncost;
      pq.emplace(-ncost, nx, ny);
    }
  }

  cout << ans << endl;
  
  return 0;
}
0