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 sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    W = W + 2
    H = H + 2
    A = [0] * H
    for i in range(H):
        if i == 0 or i == H - 1:
            A[i] = ['#'] * W
        else:
            A[i] = ['#'] + list(map(int, input().split())) + ['#']
    checked = [[False] * W for _ in range(H)]

    def dfs(s):
        dirs = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
        x, y = s
        if checked[x][y]:
            return False
        if A[x][y] == 0:
            return False

        checked[x][y] = True
        for d in dirs:
            dx, dy = d
            if A[x + dx][y + dy] == '#':
                continue
            if checked[x + dx][y + dy]:
                continue
            if A[x + dx][y + dy] == 1:
                dfs((x + dx, y + dy))
        return True

    ans = 0
    for i in range(1, H - 1):
        for j in range(1, W - 1):
            if dfs((i, j)):
                ans += 1
    print(ans)

Python: def erase(x, y):
    c[y][x] = '0'
    for dx, dy in ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)):
        nx, ny = x + dx, y + dy
        if 0 <= nx <= w -1 and 0 <= ny <= h - 1:
            if c[ny][nx] == '1':
                erase(nx, ny)

while True:
    w, h = map(int, input().split())
    c = [[i for i in input().split()] for _ in range(h)]
    ans = 0
    for y in range(h):
        for x in range(w):
            if c[y][x] == '1':
                ans += 1
                erase(x, y)
    print(ans)

Python: from collections import deque
while True:
    w,h=map(int,input().split())
    if w==0 and h==0:
        exit()
    field=[input().split() for i in range(h)]
    
    option=deque()
    for i in range(h):
        for j in range(w):
            if field[i][j]=="1":
                option.append([i,j])
                break
        else:
            continue
        break
    completed=[[0]*w for i in range(h)]
    cnt=1
    while option:
        y,x=option.pop()
        completed[y][x]=cnt
        for dy,dx in ((-1,0),(1,0),(0,-1),(0,1),(-1,-1),(1,-1),(-1,1),(1,1)):
            if 0<=y+dy<=h-1 and 0<=x+dx<=w-1 and field[y+dy][x+dx]=="1" and completed[y+dy][x+dx]==0:
                ny=y+dy
                nx=x+dx
                option.append([ny,nx])
        if len(option)==0:
            for i in range(h):
                for j in range(w):
                    if field[i][j]=="1" and completed[i][j]==0:
                        option.append([i,j])
                        cnt+=1
                        break
                else:
                    continue
                break
    ans=0
    for i in completed:
        tmp=max(i)
        ans=max(ans,tmp)
    print(ans)

Python: import sys
sys.setrecursionlimit(2500)
def dfs(i, j):
    global visited
    visited[i][j] = True
    for ii in [i - 1, i, i + 1]:
        for jj in [j - 1, j, j + 1]:
            if c[ii][jj] and not visited[ii][jj]:
                dfs(ii, jj)

w_list = []
h_list = []
c_list = []
while True:
    w, h = [int(x) for x in input().split()]
    if w == h == 0: break
    # dfsの条件分岐を減らすために、周りを海で囲む
    c = [[0 for _ in range(w + 2)]] + \
        [[0] + [int(x) for x in input().split()] + [0] for _ in range(h)] + \
        [[0 for _ in range(w + 2)]]
    w_list.append(w)
    h_list.append(h)
    c_list.append(c)

for w, h, c in zip(w_list, h_list, c_list):
    visited = [[False for _ in range(w + 2)] for _ in range(h + 2)]
    ans = 0
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            if c[i][j] == 1 and not visited[i][j]:
                ans += 1
                dfs(i, j)
    print(ans)

Python: from itertools import product
import sys

sys.setrecursionlimit(10 ** 6)

def solve(H, W, C):
    def dfs(h, w):
        if h < 0 or h >= H or w < 0 or w >= W:
            return 0
        elif C[h][w] == 0:
            return 0
        else:
            C[h][w] = 0
            for dh, dw in product((1, 0, -1), repeat = 2):
                dfs(h+dh, w+dw)
            return 1
    
    cnt = 0

    for h in range(H):
        for w in range(W):
            cnt += dfs(h, w)

    print(cnt)

A = []
while True:
    W, H = [int(i) for i in input().split()]
    if W == 0 and H == 0:
        break
    else:
        C = [[int(i) for i in input().split()] for j in range(H)]
        A.append((H, W, C))

for a in A:
    solve(*a)

Python: import sys
sys.setrecursionlimit(10 ** 7)
def dfs(h, w, grid):
    grid[h][w] = 0

    # 八方向を探索
    for dh in range(-1, 2):
        for dw in range(-1, 2):
            nh = dh + h
            nw = dw + w

            # 場外だった場合はするー(番兵)
            if nh < 0 or nw < 0:
                continue
            if grid[nh][nw] == 0:
                continue
            # 次に進む
            dfs(nh, nw, grid)
while True:
    grid = []
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    grid.append([0] * (W+2))
    grid += [[0] + list(map(int, input().split())) + [0] for _ in range(H)]
    grid.append([0] * (W+2))

    cnt = 0
    for h in range(1, H+1):
        for w in range(1, W+1):
            if grid[h][w] == 0:
                continue
            dfs(h, w, grid)
            cnt += 1
    print(cnt)