結果

問題 No.13 囲みたい!
ユーザー nsd_fb
提出日時 2015-02-19 07:50:26
言語 Python2
(2.7.18)
結果
AC  
実行時間 31 ms / 5,000 ms
コード長 1,080 bytes
コンパイル時間 137 ms
コンパイル使用メモリ 6,784 KB
実行使用メモリ 6,912 KB
最終ジャッジ日時 2024-10-13 10:41:08
合計ジャッジ時間 1,451 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

import collections

directions = ((-1, 0), (0, -1), (1, 0), (0, 1))

def bfs(sx, sy, w, h, field, visited):
    queue = collections.deque()
    queue.append((sx, sy, -1, -1))
    visited[sy][sx] = True

    while queue:
        x, y, px, py = queue.popleft()

        for dx, dy in directions:
            nx = x + dx
            ny = y + dy

            if (not (0 <= nx < w and 0 <= ny < h) or
                nx == px and ny == py or
                field[y][x] != field[ny][nx]):
                continue

            if visited[ny][nx]:
                return True

            visited[ny][nx] = True
            queue.append((nx, ny, x, y))

    return False

def solve():
    w, h = map(int, raw_input().split())
    field = [map(int, raw_input().split()) for _ in xrange(h)]
    visited = [[False] * w for _ in xrange(h)]

    for y in xrange(h):
        for x in xrange(w):
            if visited[y][x]:
                continue

            if bfs(x, y, w, h, field, visited):
                return True

    return False

print 'possible' if solve() else 'impossible'
0