結果

問題 No.3504 Insert Maze
コンテスト
ユーザー ,
提出日時 2026-04-19 00:01:30
言語 Python3
(3.14.3 + numpy 2.4.4 + scipy 1.17.1)
コンパイル:
python3 -mpy_compile _filename_
実行:
python3 _filename_
結果
TLE  
実行時間 -
コード長 2,413 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 489 ms
コンパイル使用メモリ 20,828 KB
実行使用メモリ 101,516 KB
最終ジャッジ日時 2026-04-19 00:02:12
合計ジャッジ時間 13,841 ms
ジャッジサーバーID
(参考情報)
judge1_1 / judge3_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 17 TLE * 1 -- * 67
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys
from heapq import *

def solve():
    data = sys.stdin.buffer.read().split()
    H = int(data[0]); W = int(data[1])
    grid = [data[i+2].decode() for i in range(H)]
    
    INF = float('inf')
    dist = {}
    pq = []
    
    def relax(s, c):
        if dist.get(s, INF) > c:
            dist[s] = c
            heappush(pq, (c, s))
    
    relax(('R', 0, 0, 1, 1), 0)
    
    while pq:
        d, s = heappop(pq)
        if d > dist.get(s, INF): continue
        t = s[0]
        
        if t == 'R':
            _, i, j, a, b = s
            if i == H-1 and j == W-1:
                print(d); return
            for di, dj in ((-1,0),(1,0),(0,-1),(0,1)):
                ni, nj = i+di, j+dj
                if 0 <= ni < H and 0 <= nj < W and grid[ni][nj] != '#':
                    relax(('R', ni, nj, a, b), d+1)
            if a:
                if i > 0:   relax(('VR', i-1, j, b), d+1)
                if i < H-1: relax(('VR', i,   j, b), d+1)
            if b:
                if j > 0:   relax(('VC', i, j-1, a), d+1)
                if j < W-1: relax(('VC', i, j,   a), d+1)
        
        elif t == 'VR':
            _, r, j, b = s
            if j > 0:   relax(('VR', r, j-1, b), d+1)
            if j < W-1: relax(('VR', r, j+1, b), d+1)
            if grid[r][j]   != '#': relax(('R', r,   j, 0, b), d+1)
            if grid[r+1][j] != '#': relax(('R', r+1, j, 0, b), d+1)
            if b:
                if j < W-1: relax(('VX', r, j),   d+1)
                if j > 0:   relax(('VX', r, j-1), d+1)
        
        elif t == 'VC':
            _, i, c, a = s
            if i > 0:   relax(('VC', i-1, c, a), d+1)
            if i < H-1: relax(('VC', i+1, c, a), d+1)
            if grid[i][c]   != '#': relax(('R', i, c,   a, 0), d+1)
            if grid[i][c+1] != '#': relax(('R', i, c+1, a, 0), d+1)
            if a:
                if i < H-1: relax(('VX', i,   c), d+1)
                if i > 0:   relax(('VX', i-1, c), d+1)
        
        else:  # VX(r, c)
            _, r, c = s
            relax(('VR', r, c,   0), d+1)
            relax(('VR', r, c+1, 0), d+1)
            relax(('VC', r,   c, 0), d+1)
            relax(('VC', r+1, c, 0), d+1)
            for er, ej in [(r, c), (r, c+1), (r+1, c), (r+1, c+1)]:
                if 0 <= er < H and 0 <= ej < W and grid[er][ej] != '#':
                    relax(('R', er, ej, 0, 0), d+1)
    
    print(-1)

solve()
0