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
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy

def dfs(y,x):
    if x<0 or x>=w or y<0 or y>=h:
        return
    if li[y][x] == 0:
        return
    if li[y][x] == 1:
        li[y][x] = 0
    dfs(y,x+1)
    dfs(y,x-1)
    dfs(y+1,x)
    dfs(y-1,x)
    dfs(y+1,x+1)
    dfs(y+1,x-1)
    dfs(y-1,x+1)
    dfs(y-1,x-1)
while True:
    w,h = map(int,input().split())
    if w == 0 and h == 0:
        break
    li = []
    for i in range(h):
        c = list(map(int,input().split()))
        li.append(c)
    cnt = 0
    for i in range(h):
        for j in range(w):
            if li[i][j] == 1:
                dfs(i,j)
                cnt += 1
    print(cnt)

Python: import sys
from collections import deque

sys.setrecursionlimit(10**5)

def solve():
    while 1:
        w, h = map(int, sys.stdin.readline().split())

        if w == h == 0:
            return

        room = [[int(j) for j in sys.stdin.readline().split()] for i in range(h)]

        cnt = 0

        for i in range(h):
            for j in range(w):
                if room[i][j]:
                    cnt += 1
                    bfs(w, h, room, i, j)

        print(cnt)

dx = (1, 0, -1, 0, 1, 1, -1, -1)
dy = (0, 1, 0, -1, 1, -1, 1, -1)

def bfs(w, h, room, i, j):
    room[i][j] = 0
    q = deque([(i, j)])

    while q:
        ci, cj = q.popleft()

        for k in range(len(dx)):
            ni = ci + dy[k]
            nj = cj + dx[k]

            if 0 <= ni < h and 0 <= nj < w and room[ni][nj]:
                room[ni][nj] = 0
                q.append((ni, nj))

    return

def dfs(w, h, room, i, j):
    if i < 0 or i >= h or j < 0 or j >= w or (not room[i][j]):
        return

    room[i][j] = 0

    dfs(w, h, room, i + 1, j)
    dfs(w, h, room, i - 1, j)
    dfs(w, h, room, i, j + 1)
    dfs(w, h, room, i, j - 1)
    dfs(w, h, room, i + 1, j + 1)
    dfs(w, h, room, i + 1, j - 1)
    dfs(w, h, room, i - 1, j + 1)
    dfs(w, h, room, i - 1, j - 1)

if __name__ == '__main__':
    solve()

Python: import sys #追加
sys.setrecursionlimit(500*500) #再起上限回数突破

class Node:
    def __init__(self, data):
        self.data = data
        self.f_search = False
        
    def __repr__(self):
        return str(self.data) + "," + str(self.f_search)
        

data_set = list()

while(1):
    w, h = map(int, input().split() )
    if w == 0 and h == 0:
        break

    aa = list()
    for _ in range(h):
        a = list()
        for d in map(int, input().split() ):
            a.append(Node(d))
        aa.append(a)

    data_set.append(aa)


search_vec = [(1,0), (-1,0), (0,1), (0,-1), (1,1), (-1,1), (1,-1), (-1,-1)]

iland_cnt = 0
def search_iland(iland_data):
    global iland_cnt
    for y in range(len(iland_data)):
        for x in range(len(iland_data[0])):
            if iland_data[y][x].f_search == True \
            or iland_data[y][x].data == 0:
                continue
            iland_cnt += 1
            iland_data[y][x].f_search = True
            for (dx,dy) in search_vec:
                if x+dx < 0 or y+dy < 0 \
                or x+dx >= len(iland_data[0]) \
                or y+dy >= len(iland_data): continue
                search_iland_area(iland_data, x+dx, y+dy)
            
            

def search_iland_area(iland_data, sx, sy):  
    if iland_data[sy][sx].f_search == True \
    or iland_data[sy][sx].data == 0:
        return 
    iland_data[sy][sx].f_search = True
    for (dx,dy) in search_vec:
        if sx+dx < 0 or sy+dy < 0 \
        or sx+dx >= len(iland_data[0]) \
        or sy+dy >= len(iland_data): continue
        search_iland_area(iland_data, sx+dx, sy+dy)
            
for iland in data_set:
    iland_cnt = 0
    search_iland(iland)
    print(iland_cnt)

Python: #「探索候補スタック」「探索済みリスト」「現在地点」の３点セットでとらえる
while 1:
    w,h=map(int,input().split())
    if w==h==0:
        break
    c=[list(map(int,input().split())) for _ in range(h)]
    dxdy=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]
    ans=0
    for y in range(h):
        for x in range(w):
            if c[y][x]:
                ans+=1
                stack=[]
                stack.append([x,y])
                while stack:
                    xx,yy=stack.pop()
                    for dx,dy in dxdy:
                        nx=xx+dx
                        ny=yy+dy
                        if 0<=nx<w and 0<=ny<h:
                            if c[ny][nx]:
                                c[ny][nx]=0
                                stack.append([nx,ny])
    print(ans)

Python: # coding: utf-8

import sys 

sys.setrecursionlimit(1000000)
class DFSSolver:

    def __init__(self, table, h, w):
        self.table = table
        self.count = 0
        self.h = h
        self.w = w

    def delta(self, i, j):
        candididate = [(i-1, j-1), (i-1, j), (i-1, j+1),
                       (i, j-1), (i, j+1),
                       (i+1, j-1), (i+1, j), (i+1, j+1)]
        return candididate

    def dfs(self, i, j):
        self.table[i][j] = 0
        for i, j in self.delta(i, j):
            if i < 0 or j < 0 or i >= self.h or j >= self.w:
                pass
            elif self.table[i][j] == 1:
                self.dfs(i, j)

    def solve(self):
        for i in range(self.h):
            for j in range(self.w):
                if self.table[i][j] == 1:
                    self.dfs(i, j)
                    self.count += 1
        print(self.count)


W, H = list(map(int, input().split(" ")))
while W != 0 and H != 0:
    t = []
    for _ in range(H):
        t.append(list(map(int, input().split(" "))))
    d = DFSSolver(t, H, W)
    d.solve()
    W, H = list(map(int, input().split(" ")))