結果

問題 No.697 池の数はいくつか
ユーザー lam6er
提出日時 2025-03-20 21:11:56
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,881 ms / 6,000 ms
コード長 955 bytes
コンパイル時間 204 ms
コンパイル使用メモリ 82,732 KB
実行使用メモリ 251,768 KB
最終ジャッジ日時 2025-03-20 21:13:27
合計ジャッジ時間 13,744 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

def main():
    H, W = map(int, sys.stdin.readline().split())
    grid = []
    for _ in range(H):
        row = list(map(int, sys.stdin.readline().split()))
        grid.append(row)
    
    count = 0
    dirs = [ (-1, 0), (1, 0), (0, -1), (0, 1) ]
    
    for i in range(H):
        for j in range(W):
            if grid[i][j] == 1:
                count += 1
                # Start BFS to mark all connected cells
                q = deque()
                q.append((i, j))
                grid[i][j] = 0
                while q:
                    x, y = q.popleft()
                    for dx, dy in dirs:
                        nx = x + dx
                        ny = y + dy
                        if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == 1:
                            grid[nx][ny] = 0
                            q.append((nx, ny))
    print(count)

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