結果

問題 No.2731 Two Colors
ユーザー prd_xxxprd_xxx
提出日時 2024-04-19 21:52:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 728 ms / 3,000 ms
コード長 1,793 bytes
コンパイル時間 294 ms
コンパイル使用メモリ 82,176 KB
実行使用メモリ 111,872 KB
最終ジャッジ日時 2024-10-11 14:50:35
合計ジャッジ時間 11,976 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

H,W = map(int,input().split())
A = [list(map(int,input().split())) for i in range(H)]

dij = [(0,1),(1,0),(0,-1),(-1,0)]
import heapq

C = [[-1]*W for _ in range(H)]
C[0][0] = 1
C[H-1][W-1] = 0

hq1 = []
hq0 = []
for di,dj in dij:
    ni = 0 + di
    nj = 0 + dj
    if 0 <= ni < H and 0 <= nj < W:
        heapq.heappush(hq1, (A[ni][nj],ni*W+nj))
for di,dj in dij:
    ni = H-1 + di
    nj = W-1 + dj
    if 0 <= ni < H and 0 <= nj < W:
        heapq.heappush(hq0, (A[ni][nj],ni*W+nj))

added0 = [[0]*W for _ in range(H)]
added1 = [[0]*W for _ in range(H)]
for k in range(H*W+1):
    if k%2==0:
        while hq1:
            a,v = heapq.heappop(hq1)
            i,j = divmod(v,W)
            if C[i][j] != -1:
                continue
            C[i][j] = 1
            for di,dj in dij:
                ni = i + di
                nj = j + dj
                if 0 <= ni < H and 0 <= nj < W:
                    if C[ni][nj] == 0:
                        print(k+1)
                        exit()
                    if C[ni][nj] == -1 and added1[ni][nj] == 0:
                        heapq.heappush(hq1, (A[ni][nj],ni*W+nj))
                        added1[ni][nj] = 1
            break
    else:
        while hq0:
            a,v = heapq.heappop(hq0)
            i,j = divmod(v,W)
            if C[i][j] != -1:
                continue
            C[i][j] = 0
            for di,dj in dij:
                ni = i + di
                nj = j + dj
                if 0 <= ni < H and 0 <= nj < W:
                    if C[ni][nj] == 1:
                        print(k+1)
                        exit()
                    if C[ni][nj] == -1 and added0[ni][nj] == 0:
                        heapq.heappush(hq0, (A[ni][nj],ni*W+nj))
                        added0[ni][nj] = 1
            break
0