Go: package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(getNextString(scanner), 10, 64)
	return i
}

func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}

func main() {
	fp := os.Stdin
	wfp := os.Stdout
	cnt := 0

	if os.Getenv("MASPY") == "ますピ" {
		fp, _ = os.Open(os.Getenv("BEET_THE_HARMONY_OF_PERFECT"))
		cnt = 0
	}
	if os.Getenv("MASPYPY") == "ますピッピ" {
		wfp, _ = os.Create(os.Getenv("NGTKANA_IS_GENIUS10"))
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)
	for solve(scanner, writer) {

	}
	for i := 0; i < cnt; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
	writer.Flush()
}

func solve(scanner *bufio.Scanner, writer *bufio.Writer) bool {
	sol := solver{}
	sol.w = getNextInt(scanner)
	sol.h = getNextInt(scanner)
	if sol.w == 0 && sol.h == 0 {
		return false
	}
	sol.land = makeInts(sol.h, sol.w)
	for y := 0; y < sol.h; y++ {
		for x := 0; x < sol.w; x++ {
			sol.land[y][x] = getNextInt(scanner)
		}
	}
	ans := 0
	for y := 0; y < sol.h; y++ {
		for x := 0; x < sol.w; x++ {
			if sol.land[y][x] == 0 {
				continue
			}
			ans++
			sol.dfs(y, x)
		}
	}
	fmt.Fprintln(writer, ans)
	return true
}

type solver struct {
	w, h int
	land [][]int
}

func (sol *solver) dfs(y, x int) {
	if y < 0 {
		return
	}
	if y >= sol.h {
		return
	}
	if x < 0 {
		return
	}
	if x >= sol.w {
		return
	}
	if sol.land[y][x] == 0 {
		return
	}
	sol.land[y][x] = 0
	dy := [8]int{-1, -1, -1, 0, 0, 1, 1, 1}
	dx := [8]int{-1, 0, 1, -1, 1, -1, 0, 1}
	for i := 0; i < 8; i++ {
		sol.dfs(y+dy[i], x+dx[i])
	}
}
func makeInts(h, w int) [][]int {
	index := make([][]int, h, h)
	data := make([]int, h*w, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

Python: import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    dd = [(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)]

    while True:
        w,h = LI()
        if w == 0:
            break
        a = [LI() for _ in range(h)]
        f = collections.defaultdict(bool)
        r = 0
        for i in range(h):
            for j in range(w):
                if f[(i,j)] or a[i][j] == 0:
                    continue
                r += 1
                q = [(i,j)]
                f[(i,j)] = True
                qi = 0
                while len(q) > qi:
                    ci,cj = q[qi]
                    qi += 1
                    for di,dj in dd:
                        ni = ci + di
                        nj = cj + dj
                        if 0 <= ni < h and 0 <= nj < w and a[ni][nj] == 1 and not f[(ni,nj)]:
                            f[(ni,nj)] = True
                            q.append((ni,nj))
        rr.append(r)

    return '\n'.join(map(str, rr))


print(main())

Python: import sys
sys.setrecursionlimit(50*50)

seen = []
field = []
dx =[0, 1, 1, 1, 0, -1, -1, -1]
dy =[1, 1, 0, -1, -1, -1, 0, 1]
global W, H

def dfs_grid(w, h):
    seen[h][w]=True
    #print(h, w)

    for i in range(8):
        nw = w + dx[i]
        nh = h + dy[i]

        if nw < 0 or nw >= W or nh < 0 or nh >= H:
            continue
        if field[nh][nw] == 0:
            continue
        if seen[nh][nw]:
            continue

        dfs_grid(nw, nh)
while True:
    W, H = map(int, input().split())
    cnt =0

    if W ==0 and H ==0:
        break

    for i in range(H):
        field.append(list(map(int,(input().split()))))
        seen.append([False]* W)

    #print(field)
    #print(seen)

    for i in range(H):
        for j in range(W):
            if field[i][j]==0:
                continue
            if not(seen[i][j]):
                dfs_grid(j, i)
                cnt +=1

    #print(seen)
    field.clear()
    seen.clear()
    print(cnt)

Python: while 1:
    W, H = list(map(int,input().split()))
    if W == 0:break
 
    C = [list(map(int, input().split())) for i in range(H) ]
     
    def work(x,y):
        ax = [-1, 0, 1, -1, 1, -1, 0, 1]
        ay = [-1, -1, -1, 0, 0, 1, 1, 1]
 
        if C[y][x] != 1:return False
        stack = [(x,y)]
 
        while len(stack) > 0:
            s = stack.pop(-1)
            C[s[1]][s[0]] = -1 #mark
 
            for _x in [s[0] + _x for _x in ax]:
                for _y in [s[1] + _y for _y in ay]:
                    if 0 <= _x < W and 0 <= _y < H and C[_y][_x] == 1:
                        stack.append((_x, _y))
        return True
#    def work(x,y):
#        ax = [-1, 0, 1, -1, 1, -1, 0, 1]
#        ay = [-1, -1, -1, 0, 0, 1, 1, 1]
#
#        if C[y][x] != 1:return False
#        C[y][x] = -1 #mark
#
#        for _ax in ax:
#            for _ay in ay:
#                if 0 <= _ax + x < W and 0 <= _ay + y < H:
#                    work(_ax + x, _ay + y)
#        return True
 
    cnt = 0
    for x in range(W):
        for y in range(H):
            cnt += work(x,y)
    print(cnt)

Python: def solve():
    from collections import deque
    
    while True:
        w, h = map(lambda x: int(x)+2, input().split())
        if w == 2:
            break

        result = 0
        a = ['0']*w
        for _ in [0]*(h-2):
            a += ['0'] + input().split() + ['0']
        a += ['0']*w

        for i in range(w*h):
            if a[i] != '1':
                continue
            a[i] = '0'
            result += 1
            dq = deque([i])
            while dq:
                j = dq.popleft()
                for dest in (j-w-1, j-w, j-w+1, j-1, j+1, j+w-1, j+w, j+w+1):
                    if a[dest] == '1':
                        a[dest] = '0'
                        dq.append(dest)
        print(result)


if __name__ == "__main__":
    solve()

Python: import sys
sys.setrecursionlimit(10**9)
ans = []
dx = (1,1,1,0,0,-1,-1,-1)
dy = (1,0,-1,1,-1,1,0,-1)

def dfs(x,y):
    st[x][y] = True
    for i,j in zip(dx,dy):
        nx = x + i
        ny = y + j
        if nx < 0 or h <= nx: continue
        if ny < 0 or w <= ny: continue
        if st[nx][ny]: continue
        if c[nx][ny]: dfs(nx,ny)

while True:
    w,h = map(int,input().split())
    if w == 0 and h == 0: break
    c = [[int(i) for i in input().split()] for _ in range(h)]
    st = [[False]*w for _ in range(h)]
    cnt = 0
    for i in range(h):
        for j in range(w):
            if st[i][j]: continue
            if c[i][j]:
                dfs(i,j)
                cnt += 1
    ans.append(cnt)

print("\n".join(map(str,ans)))