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: import os

import itertools
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


def solve(H, W):
    C = [list(map(int, sys.stdin.readline().split())) for _ in range(H)]

    def ok(h, w):
        return 0 <= h < H and 0 <= w < W

    def dfs(h, w):
        C[h][w] = 0
        for dh, dw in itertools.product([-1, 0, 1], repeat=2):
            if ok(h + dh, w + dw) and C[h + dh][w + dw] == 1:
                dfs(h + dh, w + dw)

    ans = 0
    for i in range(H):
        for j in range(W):
            if C[i][j] == 1:
                dfs(i, j)
                ans += 1
    return ans


while True:
    W, H = list(map(int, sys.stdin.readline().split()))
    if W == H == 0:
        break
    print(solve(H, W))

Python: import sys
sys.setrecursionlimit(10000)
def fill(y,x):
    global w,h,l
    if 0<=y<h and 0<=x+1<w and l[y][x+1]==1:
        l[y][x+1]=0
        fill(y,x+1)
    if 0<=y<h and 0<=x-1<w and l[y][x-1]==1:
        l[y][x-1]=0
        fill(y,x-1)
    if 0<=y+1<h and 0<=x<w and l[y+1][x]==1:
        l[y+1][x]=0
        fill(y+1,x)
    if 0<=y-1<h and 0<=x<w and l[y-1][x]==1:
        l[y-1][x]=0
        fill(y-1,x)
    
    if 0<=y+1<h and 0<=x+1<w and l[y+1][x+1]==1:
        l[y+1][x+1]=0
        fill(y+1,x+1)
    if 0<=y-1<h and 0<=x+1<w and l[y-1][x+1]==1:
        l[y-1][x+1]=0
        fill(y-1,x+1)
    if 0<=y+1<h and 0<=x-1<w and l[y+1][x-1]==1:
        l[y+1][x-1]=0
        fill(y+1,x-1)
    if 0<=y-1<h and 0<=x-1<w and l[y-1][x-1]==1:
        l[y-1][x-1]=0
        fill(y-1,x-1)
    
while 1:
    w,h=map(int,input().split())
    if not w and not h:break
    l=[map(int,input().split()) for _ in range(h)]

    cnt=0
    while 1:
        cds=[[i,j.index(1)] for (i,j) in enumerate(l) if 1 in j]
        if not cds:
            break
        else:
            y,x=cds[0]
        l[y][x]=0
        fill(y,x)
        cnt+=1
    print(cnt)

Python: #!python
# -*- coding: utf-8 -*-

import sys

import numpy as np

sys.setswitchinterval(10**8)


next_s = ((-1, 1), (0, 1), (1, 1),
          (-1, 0), (1, 0),
          (-1, -1), (0, -1), (1, -1))


def DFS(x, y):
    if not (0 <= x < W and 0 <= y < H):
        return
    if not map_[y, x]:
        return

    map_[y, x] = 0

    for dx, dy in next_s:
        DFS(x + dx, y + dy)


while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break

    map_ = np.array([list(map(int, input().split())) for h in range(H)])
    # print(map_)
    island_num = 0
    while np.amax(map_):
        x = np.argmax(map_) % W
        y = np.argmax(map_) // W
        # print(map_)
        # print("x: {} | y: {}".format(x, y))
        DFS(x, y)
        island_num += 1

    print(island_num)

Python: class Union_find():

    def __init__(self, num):
        self.num = num
        self.par = list(range(num))
        self.rank = [0]*num

    def find(self, x):
        px = self.par[x]
        if px == x:
            return x
        else:
            rx = self.find(px)
            self.par[x] = rx
            return rx

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] > self.rank[y]:
                self.par[y] = x
            else:
                self.par[x] = y
                if self.rank[x] == self.rank[y]:
                    self.rank[y] = self.rank[y] + 1
        return self

    def same(self, x, y):
        return self.find(x) == self.find(y)

class Group_map():
    #dx, dyは原点対象となる要素を省く
    def __init__(self, H, W, dx, dy, Mat):
        self.H = H
        self.W = W
        self.dx = dx
        self.dy = dy
        self.Mat = Mat
        self.group = Union_find(H*W)

    def to_num(self, i, j):
        return i*(self.W) + j

    def grouping(self):
        for i in range(self.H):
            for j in range(self.W):
                for k in range(len(self.dx)):
                    (ni, nj) = (i + self.dx[k], j + self.dy[k])
                    if ni in range(self.H) and nj in range(self.W) and self.Mat[i][j] == self.Mat[ni][nj]:
                        self.group.union(self.to_num(i, j), self.to_num(ni, nj))
        return self

    def num_group(self, k):
        self.grouping()
        l = set()
        for i in range(self.H):
            for j in range(self.W):
                if self.Mat[i][j] == k:
                    l.add(self.group.find(self.to_num(i, j)))
        return len(l)

    def same(self, x, y):
        return self.group.same(self.to_num(x[0], x[1]), self.to_num(y[0], y[1]))

(w, h) = map(int, input().split(" "))
while w != 0 and h != 0:
    Map = []
    for i in range(h):
        Map.append(list(map(int, input().split(" "))))
    g = Group_map(h, w, [1, 1, 1, 0], [-1, 0, 1, 1], Map)
    print(g.num_group(1))
    (w, h) = map(int, input().split(" "))