結果

問題 No.1916 Making Palindrome on Gird
ユーザー rlangevin
提出日時 2023-10-10 00:15:17
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,310 ms / 3,000 ms
コード長 1,648 bytes
コンパイル時間 425 ms
コンパイル使用メモリ 82,400 KB
実行使用メモリ 298,668 KB
最終ジャッジ日時 2024-09-12 22:42:16
合計ジャッジ時間 19,518 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

M = 205
def encode(a, b, c, d):
    now = a
    now *= M
    now += b
    now *= M
    now += c
    now *= M
    now += d
    return now

def decode(v):
    d = v % M
    v //= M
    c = v % M
    v //= M
    b = v % M
    v //= M
    return (v, b, c, d)

H, W = map(int, input().split())
S = []
for i in range(H):
    S.append(list(input()))
    
from collections import *
Q = deque()
if S[0][0] != S[-1][-1]:
    print(0)
    exit()
    
mod = 10**9 + 7
Q.append(encode(0, 0, H - 1, W - 1))
D = defaultdict(int)
D[encode(0, 0, H - 1, W - 1)] = 1
dx = [1, 0]
dy = [0, 1]
ans = 0
SS = set()
seen = set()
while Q:
    t = Q.popleft()
    sx, sy, gx, gy = decode(t)
    if gx + gy <= sx + sy + 1:
        if abs(sx - gx) + abs(sy - gy) <= 1 and t not in SS:
            SS.add(t)
            ans += D[encode(sx, sy, gx, gy)]
            ans %= mod
        continue
    
    for a in range(2):
        for b in range(2):
            nsx = sx + dx[a]
            nsy = sy + dy[a]
            ngx = gx - dx[b]
            ngy = gy - dy[b]
            d = abs(sx - gx) + abs(sy - gy)
            nd = abs(nsx - ngx) + abs(nsy - ngy)
            if nsx < 0 or nsx > H - 1 or nsy < 0 or nsy > W - 1:
                continue
            if ngx < 0 or ngx > H - 1 or ngy < 0 or ngy > W - 1:
                continue
            if nd != d - 2:
                continue
            if S[nsx][nsy] != S[ngx][ngy]:
                continue
            nt = encode(nsx, nsy, ngx, ngy)
            D[nt] += D[t]
            D[nt] %= mod
            if nt in seen:
                continue
            seen.add(nt)
            Q.append(nt)
            
print(ans)
0