結果

問題 No.3504 Insert Maze
コンテスト
ユーザー Tehom
提出日時 2026-04-18 00:30:45
言語 C++17
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 124 ms / 2,000 ms
コード長 2,308 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,435 ms
コンパイル使用メモリ 288,424 KB
実行使用メモリ 24,960 KB
最終ジャッジ日時 2026-04-18 00:30:56
合計ジャッジ時間 9,668 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 85
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
#include <atcoder/all>
using namespace std;
using namespace atcoder;
#define ll long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define repl(i,a,b) for(ll i=(a);i<(b);i++)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()

template <typename T> bool chmin(T &a,T b){if(a>b){a=b;return true;} return false;}
template <typename T> bool chmax(T &a,T b){if(a<b){a=b;return true;} return false;}


void solve(){
  // H+W-2 or H+W-1 or H+W
  int h,w; cin >> h >> w;
  vector<string> s(h);
  rep(i,0,h) cin >> s[i];
  int INF=1e9;
  vector dist(h,vector<int>(w,INF));
  queue<pair<int,int>> que;
  que.push({0,0});
  dist[0][0]=0;
  vector<int> dx={1,0,-1,0},dy={0,1,0,-1};
  while(!que.empty()){
    auto [x,y]=que.front();
    que.pop();
    rep(i,0,4){
      int nx=x+dx[i],ny=y+dy[i];
      if(0<=nx && nx<h && 0<=ny && ny<w && s[nx][ny] != '#' && chmin(dist[nx][ny],dist[x][y]+1)) que.push({nx,ny});
    }
  }
  if(dist[h-1][w-1] == h+w-2){
    cout << h+w-2 << "\n";
    return;
  }

  vector seen1(h,vector<bool>(w,false));
  vector<bool> r1(h,false);
  vector<bool> c1(w,false);
  seen1[0][0]=true;
  que.push({0,0});
  r1[0]=true;
  c1[0]=true;
  while(!que.empty()){
    auto [x,y]=que.front();
    que.pop();
    rep(i,0,2){
      int nx=x+dx[i],ny=y+dy[i];
      if(nx<h && ny<w && s[nx][ny] != '#' && !seen1[nx][ny]){
        seen1[nx][ny]=true;
        r1[nx]=true;
        c1[ny]=true;
        que.push({nx,ny});
      }
    }
  }
  vector seen2(h,vector<bool>(w,false));
  vector<bool> r2(h,false);
  vector<bool> c2(w,false);
  seen2[h-1][w-1]=true;
  que.push({h-1,w-1});
  r2[h-1]=true;
  c2[w-1]=true;
  while(!que.empty()){
    auto [x,y]=que.front();
    que.pop();
    rep(i,2,4){
      int nx=x+dx[i],ny=y+dy[i];
      if(0<=nx && 0<=ny && s[nx][ny] != '#' && !seen2[nx][ny]){
        seen2[nx][ny]=true;
        r2[nx]=true;
        c2[ny]=true;
        que.push({nx,ny});
      }
    }
  }
  rep(i,0,h-1){
    if(r1[i] && r2[i+1]){
      cout << h+w-1 << "\n";
      return;
    }
  }
  rep(i,0,w-1){
    if(c1[i] && c2[i+1]){
      cout << h+w-1 << "\n";
      return;
    }
  }

  cout << h+w << "\n";

  return;
}

int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int T=1;
  // cin >> T;
  while(T--) solve();
}
0