Go: package main

import (
	"fmt"
)

func main() {
	var h, w int
	for {
		fmt.Scan(&w, &h)
		if w == 0 && h == 0 {
			return
		}
		matrix := make([][]int, h)
		Sean := make([][]bool, h)
		for i := 0; i < h; i++ {
			matrix[i] = make([]int, w)
			Sean[i] = make([]bool, w)
			for j := 0; j < w; j++ {
				fmt.Scan(&matrix[i][j])
			}
		}
		var count int
		for i := 0; i < h; i++ {
			for j := 0; j < w; j++ {
				if matrix[i][j] == 1 && Sean[i][j] == false {
					search(i, j, h, w, matrix, Sean)
					count++
				}
			}
		}
		fmt.Println(count)
	}
}
func search(x int, y int, h int, w int, matrix [][]int, Sean [][]bool) {
	if x < 0 || y < 0 || x >= h || y >= w || matrix[x][y] == 0 {
		return
	}
	if Sean[x][y] == true {
		return
	}

	Sean[x][y] = true

	search(x+1, y, h, w, matrix, Sean)
	search(x-1, y, h, w, matrix, Sean)
	search(x, y+1, h, w, matrix, Sean)
	search(x, y-1, h, w, matrix, Sean)
	search(x+1, y-1, h, w, matrix, Sean)
	search(x-1, y+1, h, w, matrix, Sean)
	search(x+1, y+1, h, w, matrix, Sean)
	search(x-1, y-1, h, w, matrix, Sean)
}

C++: #include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int x[90][90], col[90][90], h, w, c, i, j, k, l, p, q;
queue<int>Q, R;
int main() {
	while (true) {
		c = 0;
		memset(col, 0, sizeof(col));
		cin >> w >> h;
		if (h == 0) { break; }
		for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { cin >> x[i][j]; } }
		for (i = 0; i < h; i++) {
			for (j = 0; j < w; j++) {
				if (x[i][j] == 1 && col[i][j] == 0) {
					c++;
					col[i][j] = c;
					Q.push(i * 100 + j);
					while (!Q.empty()) {
						while (!Q.empty()) {
							p = Q.front() / 100;
							q = Q.front() % 100;
							for (k = -1; k < 2; k++) {
								for (l = -1; l < 2; l++) {
									if (x[p + k][q + l] == 1 && col[p + k][q + l] == 0) {
										col[p + k][q + l] = c;
										R.push((p + k) * 100 + q + l);
									}
								}
							}
							Q.pop();
						}
						while (!R.empty()) {
							Q.push(R.front());
							R.pop();
						}
					}
				}
			}
		}
		cout << c << endl;
	}
}

C++: #include <iostream>
using namespace std;

int c[52][52];
bool c2[52][52];int w2, h2;
int dp(int h, int w);
int main()
{
	while (1) {
		
		cin >> w2 >> h2;
		if (w2 == 0 && h2 == 0)return 0;
		for (int i = 0; i < h2; i++) {
			for (int j = 0; j < w2; j++) {
				cin >> c[i][j];
			}
		}
		int ans = 0;
		for (int i = 0; i < h2; i++) {
			for (int j = 0; j < w2; j++) {
				if (!c2[i][j]) {
					
					if (c[i][j]) {
						ans++;
						dp(i, j);
					}else c2[i][j] = true;
				}
			}
			
		}
		cout << ans << endl;
		for (int i = 0; i < h2; i++) {
			for (int j = 0; j < w2; j++) {
				c2[i][j]=false;
			}
		}
	}
}
	int dp(int h, int w){
		if (h >= h2 || h < 0 || w >= w2 || w < 0)return 0;
		if (!c2[h][w]) {
			c2[h][w] = true;
			if (c[h][w]) {
				dp(h + 1, w);
				dp(h + 1, w + 1);
				dp(h + 1, w - 1);
				dp(h - 1, w);
				dp(h - 1, w + 1);
				dp(h - 1, w - 1);
				dp(h, w + 1);
				dp(h, w - 1);
			}
		}
		return 0;
	}