結果

問題 No.1916 Making Palindrome on Gird
ユーザー 👑 rin204
提出日時 2022-05-04 18:48:41
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,203 ms / 3,000 ms
コード長 1,136 bytes
コンパイル時間 144 ms
コンパイル使用メモリ 82,244 KB
実行使用メモリ 156,524 KB
最終ジャッジ日時 2024-07-03 21:50:00
合計ジャッジ時間 11,042 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

MOD = 10 ** 9 + 7

h, w = map(int, input().split())
S = [input() for _ in range(h)]

if S[0][0] != S[-1][-1]:
    print(0)
    exit()

def f(i1, i2, j1, j2):
    return ((i1 * 200 + i2) * 200 + j1) * 200 + j2

def rf(x):
    j2 = x % 200
    x //= 200
    j1 = x % 200
    x //= 200
    i2 = x % 200
    i1 = x // 200
    return i1, i2, j1, j2

dp = {f(0, 0, h - 1, w - 1): 1}
directions = [(1, 0, -1, 0), (0, 1, -1, 0), (1, 0, 0, -1), (0, 1, 0, -1)]

for _ in range((h + w) // 2 - 1):
    ndp = {}
    for tmp, v in dp.items():
        i1, j1, i2, j2 = rf(tmp)
        for di1, dj1, di2, dj2 in directions:
            ni1 = i1 + di1
            nj1 = j1 + dj1
            ni2 = i2 + di2
            nj2 = j2 + dj2
            if ni1 == h or nj1 == w or ni2 == -1 or nj2 == -1:
                continue
            if S[ni1][nj1] == S[ni2][nj2]:
                tmp = f(ni1, nj1, ni2, nj2)
                ndp[tmp] = ndp.get(tmp, 0) + v
                ndp[tmp] %= MOD
    dp = ndp

ans = 0
for tmp, v in dp.items():
    i1, j1, i2, j2 = rf(tmp)
    if abs(i1 - i2) + abs(j1 - j2) <= 1:
        ans += v
        ans %= MOD
print(ans)

0