結果

問題 No.13 囲みたい!
ユーザー titiatitia
提出日時 2021-11-02 04:36:29
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 96 ms / 5,000 ms
コード長 1,678 bytes
コンパイル時間 90 ms
コンパイル使用メモリ 13,056 KB
実行使用メモリ 12,288 KB
最終ジャッジ日時 2024-04-19 09:25:20
合計ジャッジ時間 1,880 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 29 ms
10,880 KB
testcase_01 AC 29 ms
10,880 KB
testcase_02 AC 31 ms
10,752 KB
testcase_03 AC 85 ms
11,648 KB
testcase_04 AC 96 ms
11,392 KB
testcase_05 AC 75 ms
11,904 KB
testcase_06 AC 75 ms
11,776 KB
testcase_07 AC 80 ms
12,032 KB
testcase_08 AC 84 ms
12,160 KB
testcase_09 AC 75 ms
12,288 KB
testcase_10 AC 36 ms
10,880 KB
testcase_11 AC 62 ms
11,904 KB
testcase_12 AC 30 ms
11,008 KB
testcase_13 AC 44 ms
11,264 KB
testcase_14 AC 47 ms
11,136 KB
testcase_15 AC 31 ms
10,752 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

W,H=map(int,input().split())
M=[list(map(int,input().split())) for i in range(H)]

n=W*H+3

# UnionFind

Group = [i for i in range(n+1)] # グループ分け
Nodes = [1]*(n+1) # 各グループのノードの数

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        if Nodes[find(x)] < Nodes[find(y)]:
            
            Nodes[find(y)] += Nodes[find(x)]
            Nodes[find(x)] = 0
            Group[find(x)] = find(y)
            
        else:
            Nodes[find(x)] += Nodes[find(y)]
            Nodes[find(y)] = 0
            Group[find(y)] = find(x)

COUNT=[[0]*W for i in range(H)]


for i in range(H):
    for j in range(W):
        a=M[i][j]
        count=0

        for x,y in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0<=x<H and 0<=y<W:
                if M[x][y]==a:
                    count+=1
        COUNT[i][j]=count

Q=[]
for i in range(H):
    for j in range(W):
        if COUNT[i][j]<=1:
            Q.append((i,j))

while Q:
    i,j=Q.pop()
    a=M[i][j]
    if a==-1:
        continue

    for x,y in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0<=x<H and 0<=y<W:
            if M[x][y]==a:
                COUNT[x][y]-=1
                if COUNT[x][y]<=1:
                    Q.append((x,y))
    M[i][j]=-1
    
    

for i in range(H):
    for j in range(W):
        a=M[i][j]
        if a==-1:
            continue
        count=0

        for x,y in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0<=x<H and 0<=y<W:
                if M[x][y]==a:
                    Union(x*W+y,i*W+j)

if max(Nodes)>=4:
    print("possible")
else:
    print("impossible")
0