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: #!/usr/bin/env python
# -*- coding: utf-8 -*-

def dfs(s,Map,H,W,c):
    dxdy = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)]
    for i in range(len(dxdy)):
        Map[s[0]][s[1]] = c
        nextPos = (s[0]+dxdy[i][0],s[1]+dxdy[i][1])
        if nextPos[0] >= 0 and nextPos[1] >= 0 and nextPos[0] < H and nextPos[1] < W:
            if Map[nextPos[0]][nextPos[1]] == 1:
                dfs(nextPos,Map,H,W,c)

while True:
    W,H = map(int,input().split(" "))
    if W == 0 and H == 0:
        break
    Map = [list(map(int,input().split())) for i in range(0,H)]
    c = 1
    for i in range(H):
        for j in range(W):
            if Map[i][j] == 1:
                c += 1
                dfs((i,j),Map,H,W,c)
    print(c-1)

Python: import sys
sys.setrecursionlimit(10000)
def f(x,y):
    if 0<=x<w and 0<=y<h and a[y][x]=='1':
        a[y][x]='0'
        for dx,dy in[[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]]:f(x+dx,y+dy)
while 1:
    w,h=map(int,input().split())
    if w==0:break
    a=[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: while(1):
 w,h = map(int,input().split())
 if((w == 0)and(h == 0)): break

 Map = []
 Map.append(['@']*(w+2))
 land = []
 for i in range(h):
  c = list('@'+input().replace(' ', '')+'@')
  Map.append(c)
  for j in range(w+2):
   if(c[j] == '1'): land.append([i+1,j])
 Map.append(['@']*(w+2))
 #print(land)

 #深さ優先探索
 def dfs(start_x,start_y):
  stack = []
  stack.append([start_x,start_y])
  
  while(1):      
   #stackが空になると終了
   if(stack == []): return
  
   #座標の取り出し
   cord = stack.pop()
   x,y = cord[0],cord[1]
  
   #行き止まりor海なら何もしない
   if((Map[x][y] == '0')or(Map[x][y] == '@')): continue
   #訪問済みなら何もしない
   elif(vis[x][y] == 1): continue
   else:
    vis[x][y] = 1 #訪問済みに

   #次行くところ
   vec_x = [0,0,1,-1,1,-1,1,-1]
   vec_y = [1,-1,0,0,1,-1,-1,1]
   for i in range(8):
     if(Map[x+vec_x[i]][y+vec_y[i]] == '1'):
       stack.append([x+vec_x[i],y+vec_y[i]])    
  
 ans = 0
 vis = [[0]*(w+2) for _ in range(h+2)]
 for i in range(len(land)):
  start_x,start_y = land[i][0],land[i][1]
  if(vis[start_x][start_y] == 0):
      dfs(start_x,start_y)
      ans += 1
      #print('aaa')
 print(ans)

Python: from collections import deque
QUE=deque()


while True:
    w,h=map(int,input().split())
    
    if w==h==0:
        break
    
    MAP=[list(map(int,input().split())) for i in range(h)]
    ANSLIST=[[0 for i in range(w)] for j in range(h)]

    NOW=1

    for i in range(h):
        for j in range(w):
            if MAP[i][j]==0:
                continue
            if ANSLIST[i][j]!=0:
                continue
            
            QUE.append((i,j))
            while QUE:
                i,j=QUE.pop()
                for x,y in [(i-1,j-1),(i-1,j),(i-1,j+1),(i,j-1),(i,j),(i,j+1),(i+1,j-1),(i+1,j),(i+1,j+1)]:
                    if 0<=x<h and 0<=y<w and MAP[x][y]==1 and ANSLIST[x][y]==0:
                        ANSLIST[x][y]=NOW
                        QUE.append((x,y))

            NOW+=1

    #for an in ANSLIST:
    #    print(an)

    print(NOW-1)

Python: import math
import copy
import sys
import fractions
# import numpy as np
# import statistics
import decimal
import heapq
import collections
import itertools
import bisect


# from operator import mul

sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputIntList():
    outputDataList = []
    inputData = input().split()
    outputDataList = [int(n) for n in inputData]

    return outputDataList


def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

def dfs(x, y):
    flg = False
    if data[x][y] == 0 or table[x][y] == 1:
        return False
    else:
        table[x][y] = 1
        flg = True


    for i in range(x - 1, x + 2):
        if i < 0 or i > h-1:
            continue
        for j in range(y - 1, y + 2):
            if j < 0 or j > w-1:
                continue
            if not(x == i and y == j):
                tmp = dfs(i, j)

    return flg


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

    data = getSomeInputListInt(h)
    table = [[0 for _ in range(w)] for _ in range(h)]

    ans = 0
    for i in range(h):
        for j in range(w):
            if dfs(i, j):
                ans += 1

    print(ans)