結果
| 問題 | No.124 門松列(3) | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2023-03-12 13:50:43 | 
| 言語 | PyPy3 (7.3.15) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 81 ms / 5,000 ms | 
| コード長 | 1,121 bytes | 
| コンパイル時間 | 199 ms | 
| コンパイル使用メモリ | 81,628 KB | 
| 実行使用メモリ | 77,440 KB | 
| 最終ジャッジ日時 | 2024-09-18 07:02:30 | 
| 合計ジャッジ時間 | 3,016 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge2 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 4 | 
| other | AC * 26 | 
ソースコード
from collections import *
from itertools import *
from functools import *
from heapq import *
import sys,math
input = sys.stdin.readline
W,H = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(H)]
INF = (1<<30)
dp = [[[INF]*W for i in range(H)] for j in range(10)]
v = deque()
dp[A[0][0]][0][1]=1
dp[A[0][0]][1][0]=1
v.append((0,1,A[0][0]))
v.append((1,0,A[0][0]))
def nb(x,y):
    tmp = []
    if x+1<H:
        tmp.append((x+1,y))
    if x-1>=0:
        tmp.append((x-1,y))
    if y+1<W:
        tmp.append((x,y+1))
    if y-1>=0:
        tmp.append((x,y-1))
    return tmp
while v:
    
    x,y,b = v.popleft()
    
    a = A[x][y]
    base = dp[b][x][y]
    
    for ix,iy in nb(x,y):
        
        c = A[ix][iy]
        
        X = [b,a,c]
        Y = X[:]
        Y.sort()
        if len(set(Y))!=3:
            continue
        if Y[1]!=X[1]:
            
            if dp[a][ix][iy]!=INF:
                continue
            dp[a][ix][iy] = base + 1
            v.append((ix,iy,a))
ans = min(dp[i][-1][-1] for i in range(10))
if ans==INF:
    print(-1)
else:
    print(ans)
    
            
            
            
        