結果
| 問題 | No.124 門松列(3) | 
| コンテスト | |
| ユーザー |  🍮かんプリン | 
| 提出日時 | 2020-05-22 16:32:39 | 
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 4 ms / 5,000 ms | 
| コード長 | 1,725 bytes | 
| コンパイル時間 | 1,431 ms | 
| コンパイル使用メモリ | 172,880 KB | 
| 実行使用メモリ | 5,248 KB | 
| 最終ジャッジ日時 | 2024-10-04 21:43:51 | 
| 合計ジャッジ時間 | 2,321 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge1 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 4 | 
| other | AC * 26 | 
ソースコード
/**
 *   @FileName	a.cpp
 *   @Author	kanpurin
 *   @Created	2020.05.22 16:32:32
**/
#include "bits/stdc++.h" 
using namespace std; 
typedef long long ll;
bool isKadomatsuSequence(int a,int b,int c) {
    if (a < b && b > c && a != c) {
        return true;
    }
    if (a > b && b < c && a != c) {
        return true;
    }
    return false;
}
int main() {
    int w,h;cin >> w >> h;
    vector<vector<int>> m(h,vector<int>(w));
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            cin >> m[i][j];
        }
    }
    const int dx[] = {0,1,0,-1},dy[] = {1,0,-1,0};
    constexpr int INF = 1e9 + 6;
    vector<vector<vector<int>>> dp(h,vector<vector<int>>(w,vector<int>(4,INF)));
    queue<tuple<int,int,int>> que;
    if (m[0][0] != m[0][1]) {
        dp[0][1][0] = 1;
        que.push(make_tuple(0,1,0));
    }
    if (m[0][0] != m[1][0]) {
        dp[1][0][1] = 1;
        que.push(make_tuple(1,0,1));
    }
    while(!que.empty()) {
        auto p = que.front(); que.pop();
        int nx = get<0>(p);
        int ny = get<1>(p);
        int d = get<2>(p);
        int num2 = m[nx][ny];
        int num3 = m[nx-dx[d]][ny-dy[d]];
        for (int k = 0; k < 4; k++) {
            int x = nx + dx[k], y = ny + dy[k];
            if (x >= 0 && x < h && y >= 0 && y < w && isKadomatsuSequence(m[x][y],num2,num3) && dp[x][y][k] > dp[nx][ny][d] + 1) {
                dp[x][y][k] = dp[nx][ny][d] + 1;
                que.push(make_tuple(x,y,k));
            }
        }
    }
    int ans = INF;
    for (int k = 0; k < 4; k++) {
        ans = min(ans,dp[h-1][w-1][k]);
    }
    if (ans == INF) {
        cout << -1 << endl;
    }
    else {
        cout << ans << endl;
    }
    return 0;
}
            
            
            
        