方針

DFS. 陸続きで移動できたところには、印をつけておく。

解答

なぜか sys.setrecursionlimit(100000) を設定しないと再帰が止まらなかった.

import sys
sys.setrecursionlimit(100000)

vx = [1, -1, 0, 0, 1, 1, -1, -1]
vy = [0, 0, 1, -1, 1, -1, 1, -1]


def dfs(x, y):
    c[y][x] = 0
    for dx, dy in zip(vx, vy):
        nx = x + dx
        ny = y + dy
        if nx < 0 or ny < 0 or nx >= w or ny >= h:
            continue
        if c[ny][nx] == 0:
            continue
        dfs(nx, ny)

while True:
    w, h = map(int, raw_input().split())
    if w == 0:
        break

    c = []
    for _ in range(h):
        c.append(map(int, raw_input().split()))

    cnt = 0

    for y in range(h):
        for x in range(w):
            if c[y][x] == 1:
                cnt += 1
                dfs(x, y)
    print cnt