結果

問題 No.697 池の数はいくつか
ユーザー Theta
提出日時 2023-01-27 19:22:30
言語 Python3
(3.14.3 + numpy 2.4.4 + scipy 1.17.1)
コンパイル:
python3 -mpy_compile _filename_
実行:
python3 _filename_
結果
AC  
実行時間 4,947 ms / 6,000 ms
コード長 1,668 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 487 ms
コンパイル使用メモリ 20,828 KB
実行使用メモリ 160,092 KB
最終ジャッジ日時 2026-03-16 16:03:09
合計ジャッジ時間 41,334 ms
ジャッジサーバーID
(参考情報)
judge2_0 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

from collections import deque
from itertools import combinations, product


def main():
    H, W = map(int, input().split())
    field_map = [list(map(int, input().split())) for _ in range(H)]
    searched = [[0]*W for _ in range(H)]

    pond_ctr = 0

    for height_idx, width_idx in product(range(H), range(W)):
        if field_map[height_idx][width_idx] == 0:
            continue
        if searched[height_idx][width_idx] == 1:
            continue

        pond_ctr += 1
        searching = deque(((height_idx, width_idx),))
        searched[height_idx][width_idx] = 1
        while searching:
            current_h_idx, current_w_idx = searching.popleft()
            if field_map[current_h_idx][current_w_idx] == 0:
                continue

            if current_h_idx < H-1 and searched[current_h_idx+1][current_w_idx] == 0:
                searching.append((current_h_idx+1, current_w_idx))
                searched[current_h_idx+1][current_w_idx] = 1

            if current_h_idx > 0 and searched[current_h_idx-1][current_w_idx] == 0:
                searching.append((current_h_idx-1, current_w_idx))
                searched[current_h_idx-1][current_w_idx] = 1

            if current_w_idx < W-1 and searched[current_h_idx][current_w_idx+1] == 0:
                searching.append((current_h_idx, current_w_idx+1))
                searched[current_h_idx][current_w_idx+1] = 1

            if current_w_idx > 0 and searched[current_h_idx][current_w_idx-1] == 0:
                searching.append((current_h_idx, current_w_idx-1))
                searched[current_h_idx][current_w_idx-1] = 1

    print(pond_ctr)


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