Go: ///
// File:  1160.go
// Author: ymiyamoto
//
// Created on Sun Mar  4 20:45:57 2018
//
package main

import (
	"fmt"
)

var w, h int
var graph [][]string

func dfs(visited [][]bool, x, y int) {
	visited[x][y] = true

	for i := -1; i <= 1; i++ {
		for j := -1; j <= 1; j++ {
			dx := x + i
			dy := y + j
			if 0 <= dx && dx < h && 0 <= dy && dy < w && graph[dx][dy] == "1" && !visited[dx][dy] {
				dfs(visited, dx, dy)
			}
		}
	}
}

func main() {
	for {
		fmt.Scan(&w, &h)
		if w == 0 && h == 0 {
			break
		}

		graph = make([][]string, h)
		for i := range graph {
			graph[i] = make([]string, w)
		}

		for i := 0; i < h; i++ {
			for j := 0; j < w; j++ {
				var s string
				fmt.Scan(&s)
				graph[i][j] = s
			}
		}

		visited := make([][]bool, h)
		for i := range visited {
			visited[i] = make([]bool, w)
		}

		count := 0
		for i := range graph {
			for j := range graph[i] {
				if graph[i][j] == "1" && !visited[i][j] {
					dfs(visited, i, j)
					count++
				}
			}
		}

		fmt.Println(count)
	}
}

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;
	}