Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)
var route [][]int

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func dfs(h, w int) {
	if route[h][w] == 0 {
		return
	}

	route[h][w] = 0
	for _, x := range []int{-1, 0, 1} {
		for _, y := range []int{-1, 0, 1} {
			if route[h+x][w+y] == 0 {
				continue
			}
			dfs(h+x, w+y)
		}
	}
}

func main() {
	writer := bufio.NewWriter(os.Stdout)
	for {
		w, h := scanInt(), scanInt()
		if w == 0 && h == 0 {
			break
		}

		route = make([][]int, h+2)
		route[0] = make([]int, w+2)
		for i := 1; i <= h; i++ {
			route[i] = make([]int, w+2)
			for j := 1; j <= w; j++ {
				route[i][j] = scanInt()
			}
		}
		route[h+1] = make([]int, w+2)

		total := 0
		for i := 1; i <= h; i++ {
			for j := 1; j <= w; j++ {
				if route[i][j] == 1 {
					total++
					dfs(i, j)
				}
			}
		}
		fmt.Fprintln(writer, total)
	}
	writer.Flush()
}

C++: #include<iostream>

using namespace std;

void riku(int,int);
int w,h;
int map[51][51],num;

int main(){
	//テ」ツつ?」ツ?」テ」ツ?アテ」ツδ催」ツδε」ツδ暗」ツ?ォテ」ツつづ」ツ?セテ」ツ?ィテ」ツつづ」ツ?ォテヲツ崢クテ」ツ??」ツ?ヲテ」ツ??」ツつ凝、ツコツコテ」ツ?ッテ」ツ??」ツ??
	//テァツ可ケテ」ツ?ォテ・ツ、ツ嘉」ツ?ェテヲツゥツ淌ィツδステ」ツ?ッテ、ツスツソテ」ツ?」テ」ツ?ヲテ」ツ??」ツ?ェテ」ツ??・ツ?催・ツクツーテ」ツδ療」ツδュテ」ツつーテ」ツδゥテ」ツδ?」ツ??」ツ?」テ」ツ?淌」ツ??
	cin>>w;
	cin>>h;
	while(w!=0 && h!=0){
		//テ・ツ?・テ・ツ環崚」ツ?ィテ・ツ按敕ヲツ慊淌・ツ個?
		for(int lop=0;lop<51;lop++){
			for(int lop2=0;lop2<51;lop2++){
				map[lop][lop2]=0;
			}
		}
		for(int lop=0;lop<h;lop++){
			for(int lop2=0;lop2<w;lop2++){
				cin>>map[lop][lop2];
			}
		}
		num=0;
		
		//テ」ツ?禿」ツ?禿」ツ?凝」ツつ嘉ヲツ慊ャテゥツ。ツ?
		for(int lop=0;lop<h;lop++){
			for(int lop2=0;lop2<w;lop2++){
				if(map[lop][lop2]==1){
					riku(lop,lop2);
					num++;
				}
			}
		}
		cout<<num<<endl;
		
		cin>>w;
		cin>>h;
	}
	return 0;
}

void riku(int hh,int ww){
	//テ」ツ?禿」ツ?ョテゥツ鳴「テヲツ閉ーテ」ツつ津・ツ?催・ツクツーテ」ツ?療」ツ?ヲ
	//テ、ツクツ?」ツ?、テ」ツ?ョテゥツ卍クテ」ツ?ォテ」ツ?、テ」ツ?ェテ」ツ?古」ツ?」テ」ツ?ヲテ」ツ??」ツつ凝」ツ?ィテ」ツ?禿」ツつ催」ツつ津」ツ?、テ」ツ?カテ」ツ?療」ツ?ヲテ」ツ??」ツ??
	//テ・ツ?ィテゥツδィテヲツスツーテ」ツ?療」ツ?淌」ツつ?テ」ツ?、テ」ツ?ョテゥツ卍クテ」ツ?ィテ」ツ?療」ツ?ヲテ」ツつォテ」ツつヲテ」ツδウテ」ツδ暗」ツ?療」ツ?ヲテ」ツ??」ツつ?
	map[hh][ww]=0;
	int hhh,www;
	
	/*for(int lop=-1;lop<=1;lop++){
		for(int lop2=-1;lop2<=1;lop2++){
			hhh=hh+lop2;
			www=ww+lop;
			if(0<=www && www<w && 0<=hhh && hhh<h && map[hhh][www]==1){
				riku(hhh,www);
			}
		}
	}*/
	
	for(int lop=-1;lop<=1;lop++){
		for(int lop2=-1;lop2<=1;lop2++){
			if(hh+lop>=0 && ww+lop2>=0){//テ・ツキツヲテァツォツッorテ、ツクツ甘ァツォツッテ」ツ?ョテヲツ卍づ」ツ?ッテ」ツつケテ」ツδォテ」ツδシ
				if(hh+lop<h && ww+lop2<w){//テ・ツ渉ウテァツォツッorテ、ツクツ凝ァツォツッテ」ツ?ェテ」ツつ嘉」ツつケテ」ツδォテ」ツδシ
					if(map[hh+lop][ww+lop2]==1){
						//テゥツ堋」テヲツ篠・テ」ツ?療」ツ?ヲテ」ツ??」ツつ凝」ツδ榲」ツつケテ」ツ??テ」ツ?ョテヲツ卍?
						//テ・ツ?催・ツクツーテ」ツ?療」ツ?ヲテ」ツ?敕」ツ?ョテ」ツδ榲」ツつケテ」ツ?ョテゥツ堋」テヲツ篠・テ」ツδ榲」ツつケテ」ツつ津ィツェツソテ」ツ?ケテ」ツつ?
						riku(hh+lop,ww+lop2);
					}
				}
			}
		}
	}
	
}