結果

問題 No.3504 Insert Maze
コンテスト
ユーザー テナガザル
提出日時 2026-04-17 23:13:13
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
WA  
実行時間 -
コード長 1,655 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,085 ms
コンパイル使用メモリ 193,968 KB
実行使用メモリ 42,624 KB
最終ジャッジ日時 2026-04-17 23:13:34
合計ジャッジ時間 14,120 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge2_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 21 WA * 64
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

int main()
{
  const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
  int h, w;
  cin >> h >> w;
  vector<string> s(h);
  for (int i = 0; i < h; ++i) cin >> s[i];
  auto bfs = [&](int sx, int sy) -> vector<vector<int>>
  {
    vector<vector<int>> dis(h, vector<int> (w, 1e9));
    queue<pair<int, int>> q;
    dis[sx][sy] = 0;
    for (q.push({sx, sy}); !q.empty(); q.pop())
    {
      auto [x, y] = q.front();
      for (int i = 0; i < 4; ++i)
      {
        unsigned nx = x + dx[i], ny = y + dy[i];
        if (nx >= h || ny >= w || s[nx][ny] == '#' || dis[nx][ny] <= dis[x][y] + 1) continue;
        dis[nx][ny] = dis[x][y] + 1;
        q.push({nx, ny});
      }
    }
    return dis;
  };
  vector<vector<int>> diss = bfs(0, 0), disg = bfs(h - 1, w - 1);
  for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) ++disg[i][j];
  int ans = min(h + w - 1, diss[h - 1][w - 1]);
  for (int i = 0; i < h - 1; ++i)
  {
    int mi = 1e9;
    for (int j = 0; j < w; ++j)
    {
      mi = min(mi, disg[i + 1][j]) + 1;
      ans = min(ans, diss[i][j] + mi);
    }
    mi = 1e9;
    for (int j = w - 1; j >= 0; --j)
    {
      mi = min(mi, disg[i + 1][j]) + 1;
      ans = min(ans, diss[i][j] + mi);
    }
  }
  for (int i = 0; i < w - 1; ++i)
  {
    int mi = 1e9;
    for (int j = 0; j < h; ++j)
    {
      mi = min(mi, disg[j][i + 1]) + 1;
      ans = min(ans, diss[j][i] + mi);
    }
    mi = 1e9;
    for (int j = h - 1; j >= 0; --j)
    {
      mi = min(mi, disg[j][i + 1]) + 1;
      ans = min(ans, diss[j][i] + mi);
    }
  }
  cout << ans << endl;
}
0