from collections import deque

def bfs(x,y):
    
    queue = deque()
    queue.append((x,y))
    graph[x][y] = 0
    
    dx = [0,0,-1,1,-1,1,1,-1]
    dy = [-1,1,0,0,-1,-1,1,1]
    result = 0
    
    while queue:
        
        x,y = queue.popleft()
        
        for i in range(len(dx)):
            
            nx = x + dx[i]
            ny = y + dy[i]
            
            if nx <= -1 or nx >= h or ny <= -1 or ny >= w:
                continue
            
            if graph[nx][ny] == 0:
                continue
            
            if graph[nx][ny] == 1:
                
                queue.append((nx,ny))
                graph[nx][ny] = 0
                result += 1
    return result

while True :

    w,h = map(int,input().split())
    if w + h == 0 :
        break
    graph = []
    for i in range(h):
        graph.append(list(map(int,input().split(" "))))
    
    
    cnt = []
    for i in range(h):
        for j in range(w):
            
            if graph[i][j] == 1:
                
                cnt.append(bfs(i,j))
    print(len(cnt))

Categories:

Updated: