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: def solver():
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        return None
    islands = set()
    counter = 2
    c = [[0] + [int(x) for x in input().split()] + [0]  for _ in range(h)]
    c = [[0 for _ in range(w+2)]] + c + [[0 for _ in range(w+2)]]
    for i in range(1, h+1):
        for j in range(1, w+1):
            if c[i][j] > 0:
                neighbour = {c[i-1][j-1], c[i-1][j], c[i-1][j+1], c[i][j-1]}
                if max(neighbour) > 1:
                    c[i][j] = max(neighbour)
                    if len(neighbour - {0}) > 1:
                        islands -= {max(neighbour)}
                else:
                    c[i][j] = counter
                    islands |= {counter}
                    counter += 1
    return len(islands)

outputs = []
while(True):
    ans = solver()
    if ans == None:
        break
    outputs.append(ans)
print('\n'.join(map(str, outputs)))

Python: # Union Find
#0オリジン以下注意

#xの根を求める
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
    
def unite(x, y):
    x = find(x)
    y = find(y)
    
    if x == y:
        return False
    else:
        #sizeの大きい方がx
        if par[x] > par[y]:
            x, y = y, x
        par[x] += par[y] #ここで集合の個数を更新している
        par[y] = x
        return True
    
#xとyが同じ集合に含まれているかどうかを判定(同じ集合にあればTrue)
def same(x, y):
    return find(x) == find(y)

#xが属する集合の個数
def size(x):
    return -par[find(x)]

#初期化
#根なら-size, 子なら親の頂点
################以下にコードを書く

while True:
    w, h = map(int, input().split())
    par = [-1]*(w*h)
    if (w, h) == (0, 0):
        break
    li = []
    for i in range(h):
        li.append(list(map(int, input().split())))
    for i in range(h):
        for j in range(w-1):
            if li[i][j] == li[i][j+1]:
                unite(w*i+j, w*i+j+1)
    for j in range(w):
        for i in range(h-1):
            if li[i][j] == li[i+1][j]:
                unite(w*i+j, w*i+j+w)
    for i in range(h):
        for j in range(w):
            I1 = i+1
            I2 = i-1
            J = j+1
            if 0 <= I1 and I1<h and 0<=J and J<w:
                if li[i][j] == 1 and li[I1][J] == 1:
                    unite(w*i+j, w*I1+J)
            if 0 <= I2 and I2<h and 0<=J and J<w:
                if li[i][j] == 1 and li[I2][J] == 1:
                    unite(w*i+j, w*I2+J)

                    
    #島を数える
    #陸のリスと
    li_riku = []
    for i in range(h):
        for j in range(w):
            if li[i][j]==1:
                li_riku.append(w*i+j)
    li_island = []
    sum_size = len(li_riku)
    for i in li_riku:
        k = find(i)
        if k not in li_island:
            li_island.append(k)
    print(len(li_island))

Python: import sys
sys.setrecursionlimit(10000)
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 ** 9)

first = True
while True:
    W, H = map(int, sys.stdin.readline().strip().split())
    if (W == 0) and (H == 0):
        break

    fp = [True] * (W * H)  # 探索可能示す

    M = []
    for h in range(H):
        m = list(map(int, sys.stdin.readline().strip().split()))
        M.append(m)
        for i, j in enumerate(m):
            if j == 0:
                fp[h * W + i] = False


    def dfs(u):  # u は座標
        x, y = u
        fp[y * W + x] = False  # 探索済みを示す

        for i in [-1, 0, 1]:
            x_next = x + i
            if (x_next < 0) or (x_next > W - 1):
                continue
            for j in [-1, 0, 1]:
                y_next = y + j
                if (y_next < 0) or (y_next > H - 1):
                    continue
                # print(f'y_next: {y_next}, x_next: {x_next}')
                # print(f'{fp[y_next * W + x_next]}')
                # print(f'{M[y][x]}')
                if fp[y_next * W + x_next] and (M[y][x] == 1):
                    dfs((x_next, y_next))


    count = 0
    while True in fp:
        count += 1
        # print(f'count : {count}')
        # print(f'fp: {fp}')

        y = int((fp.index(True) / W))
        x = int((fp.index(True) - y * W))
        # print(f'x: {x}, y: {y}')
        dfs((x, y))

    # if first:
    #     first = False
    # else:
    #     print('\n', end='')
    print(count, end='\n')