結果

問題 No.3199 Key-Door Grid
ユーザー ゼリトキ
提出日時 2025-07-11 22:22:13
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 106 ms / 3,000 ms
コード長 2,178 bytes
コンパイル時間 3,545 ms
コンパイル使用メモリ 282,392 KB
実行使用メモリ 23,680 KB
最終ジャッジ日時 2025-07-11 22:22:19
合計ジャッジ時間 5,575 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define ll long long
const long long mod=998244353;
const long long hmod=46216567629137;
int main(){
    cin.tie(0)->sync_with_stdio(0);
    cout.tie(0);
    int H,W,M;
    cin>>H>>W>>M;
    char S[H+2][W+2];
    pair<int,int>start,goal;
    for(int i=0;i<=H+1;i++){
        for(int j=0;j<=W+1;j++){
            if(i==0||i==H+1||j==0||j==W+1) S[i][j]='#';
            else{
                cin>>S[i][j];
                if(S[i][j]=='S') start={i,j};
                if(S[i][j]=='G') goal={i,j};
            }
        }
    }
    ll dist[H+2][W+2][M+1];
    for(int i=0;i<=H+1;i++){
        for(int j=0;j<=W+1;j++){
            for(int k=0;k<=M;k++) dist[i][j][k]=2e18;
        }
    }
    dist[start.first][start.second][0]=0;
    queue<tuple<int,int,int>>Q;
    Q.emplace(start.first,start.second,0);
    const int dx[4]={0,0,-1,1},dy[4]={-1,1,0,0};
    while(!Q.empty()){
        int h=get<0>(Q.front()),w=get<1>(Q.front()),key=get<2>(Q.front());
        Q.pop();
        for(int i=0;i<4;i++){
            int nh=h+dx[i],nw=w+dy[i];
            if(S[nh][nw]=='.' || S[nh][nw]=='S' || S[nh][nw]=='G'){
                if(dist[h][w][key]+1<dist[nh][nw][key]){
                    dist[nh][nw][key]=dist[h][w][key]+1;
                    Q.emplace(nh,nw,key);
                }
            }
            else if(S[nh][nw]>='a' && S[nh][nw]<='i'){
                int next_key=S[nh][nw]-'a'+1;
                if(key==next_key && dist[h][w][key]+1<dist[nh][nw][key]){
                    dist[nh][nw][key]=dist[h][w][key]+1;
                    Q.emplace(nh,nw,key);
                }
            }
            else if(S[nh][nw]>='1' && S[nh][nw]<='9'){
                int next_key=S[nh][nw]-'1'+1;
                if(dist[h][w][key]+1<dist[nh][nw][next_key]){
                    dist[nh][nw][next_key]=dist[h][w][key]+1;
                    Q.emplace(nh,nw,next_key);
                }
            }
        }
    }
    ll ans=2e18;
    for(int i=0;i<=M;i++){
        ans=min(ans,dist[goal.first][goal.second][i]);
    }
    if(ans==2e18) cout<<"-1\n";
    else cout<<ans<<"\n";
}
0