https://www.acmicpc.net/problem/4963
def bfs(i, j):
graph[i][j] = 0
queue = [[i,j]]
while queue:
a, b = queue[0][0], queue[0][1]
del queue[0]
for dx in range(-1,2,1):
for dy in range(-1,2,1):
if not(dx == 0 and dy ==0):
x = a + dx
y = b + dy
if 0 <= x < h and 0 <= y <w and graph[x][y] == 1:
graph[x][y] = 0
queue.append([x,y])
while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
graph = []
for _ in range(h):
graph.append(list(map(int, input().split())))
result = 0
for i in range(h):
for j in range(w):
if graph[i][j]==1:
bfs(i,j)
result += 1
print(result)