結果

問題 No.697 池の数はいくつか
ユーザー Hitoshi Hayakawa
提出日時 2019-09-06 16:04:41
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,295 ms / 6,000 ms
コード長 1,824 bytes
コンパイル時間 373 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 277,760 KB
最終ジャッジ日時 2024-11-08 08:22:04
合計ジャッジ時間 18,066 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################

class UnionFind:
    def __init__(self, N):
        self.parent = [i for i in range(N)]

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if (x == y):
            return

        self.parent[x] = y

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def delete(self, idx):
        self.parent[idx] = -1

H, W = map(int, input().split())
uf = UnionFind(H*W)

pond = [ [0 for _ in range(W)] for _ in range(H) ]

idx = 0
for i in range(H):
    A = list(map(int, input().split()))

    tmp = []
    for j in range(len(A)):
        if A[j] == 0:
            tmp.append(-1)
        else:
            tmp.append(idx)
        idx += 1

    pond[i] = tmp

#print(pond)
#exit()


idx = -1
for h in range(H):
    for w in range(W):
        idx += 1
        if pond[h][w] == -1:
            # 対象外のは壊す
            uf.delete(idx)
            continue

        if h > 0:
            if pond[h-1][w] > -1:
                uf.unite(pond[h-1][w], pond[h][w])
        if w > 0:
            if pond[h][w-1] > -1:
                uf.unite(pond[h][w-1], pond[h][w])
        if w < W-1:
            if pond[h][w+1] > -1:
                uf.unite(pond[h][w+1], pond[h][w])
        if h < H-1:
            if pond[h+1][w] > -1:
                uf.unite(pond[h+1][w], pond[h][w])


#print(uf.parent)

count = 0
for i in range(H*W):
    if uf.parent == -1:
        continue

    if uf.find(i) == i:
        count += 1

if count == H*W:
    print(0 if pond[0][0] == 0 else 1)
else:
    print(count)
0