Go: ///
// File:  1160.go
// Author: ymiyamoto
//
// Created on Sun Mar  4 20:45:57 2018
//
package main

import (
	"fmt"
)

var w, h int
var graph [][]string

func dfs(visited [][]bool, x, y int) {
	visited[x][y] = true

	for i := -1; i <= 1; i++ {
		for j := -1; j <= 1; j++ {
			dx := x + i
			dy := y + j
			if 0 <= dx && dx < h && 0 <= dy && dy < w && graph[dx][dy] == "1" && !visited[dx][dy] {
				dfs(visited, dx, dy)
			}
		}
	}
}

func main() {
	for {
		fmt.Scan(&w, &h)
		if w == 0 && h == 0 {
			break
		}

		graph = make([][]string, h)
		for i := range graph {
			graph[i] = make([]string, w)
		}

		for i := 0; i < h; i++ {
			for j := 0; j < w; j++ {
				var s string
				fmt.Scan(&s)
				graph[i][j] = s
			}
		}

		visited := make([][]bool, h)
		for i := range visited {
			visited[i] = make([]bool, w)
		}

		count := 0
		for i := range graph {
			for j := range graph[i] {
				if graph[i][j] == "1" && !visited[i][j] {
					dfs(visited, i, j)
					count++
				}
			}
		}

		fmt.Println(count)
	}
}

Python: from queue import Queue

def dfs(x,y,c):
    que = Queue()
    que.put((x, y))

    while not que.empty():
        x, y = que.get()
        if c[x][y] == 0:
            continue

        c[x][y] = 0
        for dx in range(-1, 2):
            for dy in range(-1, 2):
                sx, sy = x + dx, y + dy
                if sx < 0 or sx >= h or sy < 0 or sy >= w:
                    continue
                que.put((sx, sy))
    return c

while True:
    w,h = map(int,input().split())
    if w == h == 0:
        break
    wh = w * h
    c = [list(map(int,input().split())) for _ in range(h)]
    ans = 0
    for x in range(h):
        for y in range(w):
            if c[x][y] == 0:
                continue
            ans += 1
            c = dfs(x,y,c)
    print(ans)

Python: import sys
from pprint import pprint


class UnionFind:
    def __init__(self):
        self._parent = {}
        self._rank = {}
        self._equiv = {}
    
    def _find(self, x):
        if self._parent[x] == x:
            return self._parent[x]
        else:
            p = self._find(self._parent[x])
            self._parent[x] = p
            return p
    
    def _set_parent(self, child, parent):
        self._parent[child] = parent
        self._equiv[parent].update(self._equiv.pop(child))
    
    def _union(self, x, y):
        x = self._find(x)
        y = self._find(y)
        if x == y: return
        if self._rank[x] > self._rank[y]:
            self._set_parent(y, x)
        elif  self._rank[x] < self._rank[y]:
            self._set_parent(x, y)
        else:
            self._set_parent(x, y)
            self._rank[x] += 1
    
    def _make_set(self, x):
        self._parent[x] = x
        self._rank[x] = 0
        self._equiv[x] = {x}
    
    def unite(self, *elements):
        if not elements: return
        for x in elements:
            if x in self._parent: continue
            self._make_set(x)
        x0 = elements[0]
        for x in elements[1:]:
            self._union(x0, x)
    
    def groups(self):
        return [set(e) for e in self._equiv.values()]


def pairs(ncol, nrow):
    # ?????????
    for x in range(ncol - 1):
        for y in range(nrow):
            yield [(x, y), (x + 1, y)]

    # ?????????
    for x in range(ncol):
        for y in range(nrow - 1):
            yield [(x, y), (x, y + 1)]

    # ???????????????
    for x in range(ncol - 1):
        for y in range(nrow - 1):
            yield [(x, y), (x + 1, y + 1)]

    # ???????????????
    for x in range(ncol - 1):
        for y in range(1, nrow):
            yield [(x, y), (x + 1, y - 1)]


def solve(ncol, nrow, rows):
 
    f = UnionFind()
    for x in range(ncol):
        for y in range(nrow):
            if rows[y][x]:
                f.unite((x, y))
    for (x1, y1), (x2, y2) in pairs(ncol, nrow):
        if rows[y1][x1] and rows[y2][x2]:
            f.unite((x1, y1), (x2, y2))
    return len(f.groups())


def main():
    while True:
        ncol, nrow = map(int, input().split())
        if ncol == 0 and nrow == 0:
            break
        rows = []
        for _ in range(nrow):
            row = list(map(int, input().split()))
            rows.append(row)
        print(solve(ncol, nrow, rows))

main()

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


def search(n, m, tile, N, M):
    for dy, dx in zip([-1, -1, -1, 0, 0, 1, 1, 1], [-1, 0, 1, -1, 1, -1, 0, 1]):
        if 0 <= dy + n < N and 0 <= dx + m < M:
            if tile[dy + n][dx + m] == '1':
                tile[dy + n][dx + m] = '2'
                search(dy + n, dx + m, tile, N, M)


while True:
    M, N = map(int, input().split())
    if M == 0 and N == 0:
        break
    tile = [input().split() for n in range(N)]
    ans = 0
    for n in range(N):
        for m in range(M):
            if tile[n][m] == '1':
                tile[n][m] = '2'
                search(n, m, tile, N, M)
                ans += 1
    print(ans)

Python: def bfs(field, start_i, start_j, w, h):
    OFFSETS = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

    queue = [(start_i,start_j)]

    while len(queue) > 0:
        i, j = queue.pop()
        field[i][j] = "0"

        for di, dj in OFFSETS:
            if i+di < 0 or i+di >= h:
                continue
            if j+dj < 0 or j+dj >= w:
                continue
            if field[i+di][j+dj] == "1":
                queue.append((i+di, j+dj))


def main():
    while True:
        w, h = [int(s) for s in input().strip().split()]

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

        num_island = 0
    
        field = []
        for _ in range(h):
            field.append(input().strip().split())
       
        #print(field) 
        for i in range(h):
            for j in range(w):
                if field[i][j] == "1":
                    num_island += 1
                    bfs(field, i, j, w, h)
        
        print(num_island)


if __name__ == "__main__":
    main()

Python: # -*- coding: utf-8 -*-
#150 島は幾つある？
h,w=1,1

count=0
anser=0

def search(x,y):
    #マップの外側か壁の場合は何もしない
    #print(x,y)

    global count
    count+=1
    if x<0 or x>w-1 or y<0 or y>h-1 or map_data[y][x]==0:
 
        return
        
    
    #以前に到達していたら何もしない
    if reached[y][x] ==0:
         return

    reached[y][x]=0
    
    #print("aa")



    search(x+1,y)#右
    search(x-1,y)#左
    search(x,y+1)#上
    search(x,y-1)#下
    search(x-1,y-1)
    search(x-1,y+1)
    search(x+1,y-1)
    search(x+1,y+1)


while h!=0 and w!=0: 
    anser=0
    count=1
    #グラフの入力方法------

    w,h=map(int ,raw_input().split())
    if h==0 and w==0:
        break

    map_data = [[0]*w for _ in range(h)]
    reached = [[1]*w for _ in range(h)]

    for i in range(h):
        ct = raw_input().split()
       
        for j in range(w):
            map_data[i][j] = int(ct[j])
            reached [i][j]=int(ct[j])
            if ct[j]==1:
                sx=j
                sy=i

    t=0
    a=0
    while a<=h:
       if 1 in reached[t%h]:         
            search(reached[t%h].index(1),t%h)
            anser+=1
            #print("count",count)
            count=1
            a=0
       elif count==h:
                break
       t+=1
       a+=1

    print(anser)