Go: package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	resolve()
}

func resolve() {
	results := []int{}
	for true {
		w, h := scanInt(sc), scanInt(sc)
		if w == 0 && h == 0 {
			break
		}
		grid := make([][]int, h)
		for i := 0; i < h; i++ {
			grid[i] = make([]int, w)
			for j := 0; j < w; j++ {
				grid[i][j] = scanInt(sc)
			}
		}
		num := 0
		for i := range loop0(h) {
			for j := range loop0(w) {
				start := pos{y: i, x: j}
				if grid[start.y][start.x] == 0 {
					continue
				}
				num++
				_dfs(grid, w, h, start)
			}
		}
		results = append(results, num)
	}
	for _, v := range results {
		fmt.Println(v)
	}
	return
}

func _dfs(grid [][]int, w, h int, start pos) {
	grid[start.y][start.x] = 0
	for _, df := range []pos{
		pos{1, 0}, pos{-1, 0},
		pos{0, -1}, pos{0, 1},
		pos{1, 1}, pos{-1, -1},
		pos{-1, 1}, pos{1, -1},
	} {
		np := addPos(start, df)
		if np.y < 0 || h <= np.y || np.x < 0 || w <= np.x {
			continue
		}
		if grid[np.y][np.x] == 0 {
			continue
		}
		_dfs(grid, w, h, np)
	}
}

type pos struct{ x, y int }

func addPos(p, d pos) pos {
	return pos{
		x: p.x + d.x,
		y: p.y + d.y,
	}
}

func loop0(n int) chan int {
	return loop(0, n-1, 1)
}

func loop1(n int) chan int {
	return loop(1, n, 1)
}

func loop(s, e, d int) chan int {
	ch := make(chan int)
	go func() {
		for i := s; i <= e; i += d {
			ch <- i
		}
		close(ch)
	}()
	return ch
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

Python: import sys

def solve():
    while 1:
        w, h = map(int, sys.stdin.readline().split())

        if w == h == 0:
            return

        room = [[int(j) for j in sys.stdin.readline().split()] for i in range(h)]

        cnt = 0

        for i in range(h):
            for j in range(w):
                if room[i][j]:
                    cnt += 1
                    dfs(w, h, room, i, j)

        print(cnt)

def dfs(w, h, room, i, j):
    if i < 0 or i >= h or j < 0 or j >= w or (not room[i][j]):
        return

    room[i][j] = 0

    dfs(w, h, room, i + 1, j)
    dfs(w, h, room, i - 1, j)
    dfs(w, h, room, i, j + 1)
    dfs(w, h, room, i, j - 1)
    dfs(w, h, room, i + 1, j + 1)
    dfs(w, h, room, i + 1, j - 1)
    dfs(w, h, room, i - 1, j + 1)
    dfs(w, h, room, i - 1, j - 1)

if __name__ == '__main__':
    solve()

Python: import queue
def allvisited():
    for i in range(w):
        for j in range(h):
            if (visited[i][j]==False and s[i][j]=='1'):
                return (False,i,j)
    else:
         return (True,-1,-1)
        
def legal(pos):
    if(0<=pos[0]<w) and (0<=pos[1]<h) and s[pos[0]][pos[1]]=='1' and visited[pos[0]][pos[1]]==False:
        return True
    else:
        return False
    
d=[[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,1],[1,-1],[-1,-1]]
while(1):
    h,w=map(eval,input().split())
    if (w==0 and h==0): break
    s=[]
    for i in range(w):
        s.append(input().split())
    #print(s)
    Q=queue.Queue()
    visited=[]
    for i in range(w):
        visited.append([False]*h)
    #print(visited)
    count=0
    while(1):
        a=allvisited()
        if (a[0]==False):
            Q.put((a[1],a[2]))
            visited[a[1]][a[2]]=True
            count+=1
        else:
            break
        while(not Q.empty()):
            now=Q.get()
            for i in range(8):
                new=(now[0]+d[i][0],now[1]+d[i][1])
                if(legal(new)):
                    Q.put(new)
                    visited[new[0]][new[1]]=True
    print(count)

Python: from collections import deque

y = [1,1,1,0,0,-1,-1,-1]
x = [-1,0,1,-1,1,-1,0,1]

def main():
    w,h = 0,0
    c = []

    def check(i,j):
        return 0<=i and i<h and 0<=j and j<w

    def bfs(a,b):
        d = deque()
        d.append([a,b])
        while len(d):
            i,j = d.popleft()
            if not check(i,j):continue
            if c[i][j]==0:continue
            c[i][j]=0
            for k in range(8):
                d.append([i+y[k],j+x[k]])

    while True:
        w,h = map(int,input().split())
        if w==0 and h==0: break
        c = []
        res = 0
        for _ in range(h):
            c.append(list(map(int,input().split())))
        for i in range(h):
            for j in range(w):
                if c[i][j]==1:
                    bfs(i,j)
                    res+=1
        print(res)

if __name__ == '__main__':
    main()

Python: import sys
sys.setrecursionlimit(10**8)

def dfs_fill(m, x, y):
    if not (0 <= x < W and 0 <= y < H) or m[y][x] == "0":
        return False
    m[y][x] = "0"
    for dx in range(-1, 2):
        for dy in range(-1, 2):
            if dx == dy == 0:
                continue
            dfs_fill(m, x+dx, y+dy)

while True:
    W, H = map(int, input().split())
    if W == H == 0:
        break
    C = [input().split() for _ in range(H)]

    count = 0
    for y in range(H):
        for x in range(W):
            # print("\n".join(["".join(c) for c in C]))
            if C[y][x] == "1":
                count += 1
                dfs_fill(C, x, y)

    print(count)

Python: import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappop, heappush, heapify, heappushpop
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

dx = [0, 1, 0, -1, 1, 1, -1, -1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
def DFS(i, j):
	global w, h
	for x in range(8):
		nx = j + dx[x]
		ny = i + dy[x]
		if 0 <= nx <= w-1 and 0 <= ny <= h-1 and c[ny][nx]==1:
			c[ny][nx] = 0
			DFS(ny, nx)

ans = []
while 1:
	w, h = MAP()
	if [w, h] == [0, 0]:
		break
	c = [LIST() for _ in range(h)]

	count = 0
	for i in range(h):
		for j in range(w):
			if c[i][j] == 1:
				c[i][j] = 0
				DFS(i, j)
				count += 1
	ans.append(count)

for i in ans:
	print(i)

Python: import sys
sys.setrecursionlimit(1<<32)
def f(x,y):
    a[y][x]='0'
    for dx,dy in[[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]]:
        dx+=x;dy+=y
        if 0<=dx<w and 0<=dy<h and a[dy][dx]=='1':f(dx,dy)
while 1:
    w,h=map(int,input().split())
    if w==0:break
    a=[list(input().split()) for _ in[0]*h];b=0
    for i in range(w):
        for j in range(h):
            if a[j][i]=='1':
                b+=1;f(i,j)
    print(b)

Python: import sys
sys.setrecursionlimit(10**7)


def DFS(x,y):
    color[x][y]="gray"
    for i,j in [[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,-1],[1,0],[1,1]]:
        X,Y=x+i,y+j
        if 0<=X<h and 0<=Y<w:
            if C[X][Y]==1 and color[X][Y]=="white":
                DFS(x+i,y+j)
    color[x][y]="black"


while 1:
    w,h=map(int,input().split())
    if w==0 and h==0:break
    C=[list(map(int,input().split())) for _ in range(h)]
    color=[["white" for _ in range(w)] for _ in range(h)]
    cnt=0
    for i in range(h):
        for j in range(w):
            if color[i][j]=="white" and C[i][j]==1:
                DFS(i,j)
                cnt +=1
    print(cnt)