Go: // AOJ 1160: How Many Islands? http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1160

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
	"strconv"
)

var SEA = 0
var LAND = 1

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

func discoverIslands(M, V [][]int, H, W int) int {
	// 島を探す
	queue := list.New()
	islands := 0
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			// 訪問済みの土地ならスキップ
			if V[i][j] == 1 {
				continue
			}

			// 訪問中の土地が海なら訪問済みにしてスキップ
			if M[i][j] == SEA {
				V[i][j] = 1
				continue
			}

			// 未訪問の陸地が見つかったので
			// 島の数を1つ増やし、この陸地から辿れる陸地を訪問していく
			islands++
			queue.PushBack([]int{i, j})

			for queue.Len() > 0 {
				cur := queue.Remove(queue.Front()).([]int)
				h, w := cur[0], cur[1]
				if V[h][w] == 1 {
					continue
				}
				V[h][w] = 1

				// 全方向に未訪問の陸地がないか探索
				for v := -1; v <= 1; v++ {
					for l := -1; l <= 1; l++ {
						dh := h + v
						dw := w + l
						if M[dh][dw] == LAND && V[dh][dw] == 0 {
							queue.PushBack([]int{dh, dw})
						}
					}
				}
				/*
					if M[h-1][w] == LAND {
						queue.PushBack([]int{h - 1, w})
					}
					if M[h-1][w+1] == LAND {
						queue.PushBack([]int{h - 1, w + 1})
					}
					if M[h][w+1] == LAND {
						queue.PushBack([]int{h, w + 1})
					}
					if M[h+1][w+1] == LAND {
						queue.PushBack([]int{h + 1, w + 1})
					}
					if M[h+1][w] == LAND {
						queue.PushBack([]int{h + 1, w})
					}
					if M[h+1][w-1] == LAND {
						queue.PushBack([]int{h + 1, w - 1})
					}
					if M[h][w-1] == LAND {
						queue.PushBack([]int{h, w - 1})
					}
					if M[h-1][w-1] == LAND {
						queue.PushBack([]int{h - 1, w - 1})
					}
				*/
			}
		}
	}
	return islands
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	for {
		W, H := nextInt(sc), nextInt(sc)

		if W == 0 && H == 0 {
			break
		}
		// Initialize map and visted list
		M := make([][]int, H+2)
		V := make([][]int, H+2)
		for i := 0; i < H+2; i++ {
			M[i] = make([]int, W+2)
			V[i] = make([]int, W+2)
		}
		for i := 1; i <= H; i++ {
			for j := 1; j <= W; j++ {
				M[i][j] = nextInt(sc)
			}
		}

		islands := discoverIslands(M, V, H, W)

		fmt.Println(islands)
	}
}

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

def dfs(s,Map,H,W,c):
    dxdy = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)]
    for i in range(2):
        Map[s[0]][s[1]] = c
        nextPos = (s[0]+dxdy[i][0],s[1]+dxdy[i][1])
        if nextPos[0] >= 0 and nextPos[1] >= 0 and nextPos[0] < H and nextPos[1] < W:
            if Map[nextPos[0]][nextPos[1]] == 1:
                dfs(nextPos,Map,H,W,c)

while True:
    W,H = map(int,input().split(" "))
    if W == 0 and H == 0:
        break
    Map = [list(map(int,input().split())) for i in range(0,H)]
    c = 1
    for i in range(H):
        for j in range(W):
            if Map[i][j] == 1:
                c += 1
                dfs((i,j),Map,H,W,c)
    print(c-1)

Python: import sys
sys.setrecursionlimit(100000)


def dfs(x,graph,seen,nxt):
    seen[x]=1
    if x in nxt:
        nxt.remove(x)
    nxt+=[y for y in graph[x] if not seen[y] and y not in nxt]
    while nxt :
        dfs(nxt.pop(-1),graph,seen,nxt)


def island_count(w,h):
    lst=[list(map(int,input().split())) for _ in range(h)]
    graph={}
    for i in range(h):
        for j in range(w):
            if not lst[i][j] : continue
            graph[(i,j)]=[]
            for k in range(-1,2):
                for l in range(-1,2):
                    if k==0 and l==0 : continue
                    if i+k<0 or j+l<0 : continue
                    try:
                        if lst[i+k][j+l]:
                            graph[(i,j)].append((i+k,j+l))
                    except IndexError:
                        continue
    #print(graph)
    seen={x:0 for x in graph}
    sm=0
    nxt=[]
    for x in seen:
        if seen[x] : continue
        if not seen[x]:
            dfs(x,graph,seen,nxt)
            sm+=1

    print(sm)






while 1 :
    w,h=map(int,input().split())
    if (w,h)==(0,0) : break
    island_count(w,h)

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)