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: # 25

import sys
import itertools

sys.setrecursionlimit(10**7) #再帰関数の呼び出し制限
while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    c_l = [[int(x) for x in input().split()] for y in range(h)]
    s_l = [[True] * w for x in range(h)]
    v_l = list(itertools.product([-1,0,1],repeat=2))
    
    def dfs(y, x):
        if x < 0 or y < 0 or x >=w or y >= h:
            return False
        if not s_l[y][x]:
            return False
        s_l[y][x] = False
        _c = c_l[y][x]
        if _c == 0:
            return False
        for _v in v_l:
            dfs(y+_v[0],x+_v[1])
        return True

    ans = 0
    for i in range(h):
        for j in range(w):
            if s_l[i][j]:
                if dfs(i, j):
                    ans += 1
                    
    print(ans)

Python: 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 queue

def proceess(start_x,start_y):
    #print("start_x : " + str(start_x) + ", start_y : " + str(start_y))
    #insland = []
    #insland.append([start_x,start_y])
    new_island = queue.Queue()
    map[start_x][start_y] = 0
    new_island.put([start_x,start_y])
    while True:
        ob = new_island.get()
        x = ob[0]
        y = ob[1]
        #print("x : " + str(x) + ", y : " + str(y))

        for i in [-1,0,1]:
            for j in [-1,0,1]:
                nx = x + i
                ny = y + j

                if nx >= 0 and ny >= 0 and nx < h and ny < w:
                    if map[nx][ny] == 1:
                        #insland.append([nx,ny])
                        #print("ny : " + str(ny) + ", nx : " + str(nx))
                        new_island.put([nx,ny])
                        map[nx][ny] = 0

        #print("end 8 count.")
        if new_island.empty():
            break

while True:
    map = []

    tmp = input().split(" ")
    w = int(tmp[0])
    h = int(tmp[1])

    if w == 0 and h == 0:
        break


    for j in range(h):
        nova = []
        arm = input()
        for k in arm.split(" "):
            #k.rstrip('\n')
            nova.append(int(k))
        map.append(nova)

    #print(map)

    count = 0
    for i in range(h):
        for j in range(w):
            if map[i][j] == 1:
                #print("i : " + str(i) + ", j : " + str(j))
                proceess(i,j)
                count += 1

    print(count)

Python: # -*- coding: utf-8 -*-
import sys
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()


def main():
    while True:
        W,H=map(int,input().split())
        if W==H==0:
            exit()
        C=[[] for _ in range(H+2)]
        C[0]=C[H+1]=[-1]*(W+2)
        used=[[False]*(W+2) for _ in range(H+2)]
        rands=[]
        for column in range(1,H+1):
            C[column]=[-1]+list(map(int,input().split()))+[-1]
            for row,x in enumerate(C[column]):
                if x==1:
                    rands.append((column,row))

        ans=0
        
        if rands:
            s=[]
            while rands:
                y,x=rands.pop()
                if used[y][x]:
                    continue
                s.append((y,x))
                while s:
                    y,x=s.pop()
                    if used[y][x]:
                        continue
                    used[y][x]=True
                    for dy in range(-1,2):
                        for dx in range(-1,2):
                            ny,nx=y+dy,x+dx
                            if dy==dx==0 or used[ny][nx]:
                                continue
                            if C[ny][nx]==1:
                                s.append((ny,nx))
                ans+=1
        print(ans)
                

if __name__ == '__main__':
    main()

Python: import sys
input = lambda: sys.stdin.readline().rstrip() 

def resolve():
    while True:
        w, h = map(int, input().split())
        if w==h==0:
            break
        c = [list(map(int, input().split())) for _ in range(h)]

        stk = []
        visited = [[False]*w for _ in range(h)]
        dir = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1))

        ans = 0

        for i in range(h):
            for j in range(w):
                if c[i][j]==1 and not visited[i][j]:
                    stk.append((i, j))
                    while len(stk)>0:
                        a = stk.pop()
                        visited[a[0]][a[1]] = True
                        for d in dir:
                            ad = (a[0]+d[0], a[1]+d[1])
                            if 0<=ad[0]<h and 0<=ad[1]<w and c[ad[0]][ad[1]]==1 and not visited[ad[0]][ad[1]]:
                                stk.append(ad) 
                    ans += 1

        print(ans)

if __name__ == '__main__':
    resolve()