結果

問題 No.13 囲みたい!
ユーザー はむ吉🐹はむ吉🐹
提出日時 2016-05-27 09:14:42
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 60 ms / 5,000 ms
コード長 1,867 bytes
コンパイル時間 93 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 12,800 KB
最終ジャッジ日時 2024-04-21 12:26:33
合計ジャッジ時間 1,590 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 31 ms
11,008 KB
testcase_01 AC 31 ms
11,008 KB
testcase_02 AC 35 ms
11,008 KB
testcase_03 AC 48 ms
12,288 KB
testcase_04 AC 34 ms
11,008 KB
testcase_05 AC 60 ms
12,800 KB
testcase_06 AC 36 ms
11,392 KB
testcase_07 AC 58 ms
12,672 KB
testcase_08 AC 56 ms
12,148 KB
testcase_09 AC 57 ms
12,024 KB
testcase_10 AC 35 ms
11,136 KB
testcase_11 AC 52 ms
11,776 KB
testcase_12 AC 32 ms
11,008 KB
testcase_13 AC 41 ms
11,520 KB
testcase_14 AC 40 ms
11,520 KB
testcase_15 AC 32 ms
11,008 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3

import array
import collections
import itertools


REC_LIMIT = 10000
DELTAS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
UNDEF = (-1, -1)


class Solver(object):

    def __init__(self, width, height, field):
        self.width = width
        self.height = height
        self.field = field
        self.visited = collections.defaultdict(bool)
        self.pred = collections.defaultdict(lambda: UNDEF)

    def in_field(self, r, c):
        return 0 <= r < self.height and 0 <= c < self.width

    def in_cycle(self, r0, c0, num):
        self.visited[(r0, c0)] = True
        q = collections.deque()
        q.append((r0, c0))
        while q:
            (r1, c1) = q.pop()
            for dr, dc in DELTAS:
                (r, c) = (r1 + dr, c1 + dc)
                if not self.in_field(r, c):
                    continue
                elif self.field[r][c] != num:
                    continue
                if self.visited[(r, c)]:
                    if self.pred[(r1, c1)] != (r, c):
                        return True
                    else:
                        continue
                self.visited[(r, c)] = True
                self.pred[(r, c)] = (r1, c1)
                q.append((r, c))
        return False

    def judge(self):
        rcs = itertools.product(range(self.height), range(self.width))
        for r, c in rcs:
            if not self.visited[(r, c)]:
                answer = self.in_cycle(r, c, self.field[r][c])
                if answer:
                    return True
        else:
            return False


def main():
    width, height = map(int, input().split())
    field = [array.array("I", map(int, input().split()))
             for _ in range(height)]
    solver = Solver(width, height, field)
    print("possible" if solver.judge() else "impossible")


if __name__ == '__main__':
    main()
0