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

C++: #define _CRT_SECURE_NO_WARNINGS
#include"bits/stdc++.h"
#define INF          1e9
#define INFLL        1e18
#define EPS          1e-9
#define MOD          1000000007
#define REP(i,n)     for(ll i=0,i##_len=(n);i<i##_len;++i)
#define REP1(i,n)    for(ll i=1,i##_len=(n);i<=i##_len;++i)
#define REPR(i,n)    for(ll i=(n)-1;i>=0;--i)
#define REPR1(i,n)   for(ll i=(n);i>0;--i)
#define REPC(i,obj)  for(auto i:obj)
#define ALL(obj)     (obj).begin(),(obj).end()
#define SETP(n)      cout<<fixed<<setprecision(n)
#define VV(T,h,w)    vector<vector<T>>(h,vector<T>(w))
#define VVI(T,h,w,i) vector<vector<T>>(h,vector<T>(w,i))
using namespace std;
using ll = long long;
template<typename T = ll>inline T in() { T ret; cin >> ret; return ret; }

int main()
{
    while (true) {
        ll w = in(), h = in();
        if (w == 0 && h == 0)break;
        auto mp = VVI(ll, h + 2, w + 2, 0);
        REP(i, h) {
            REP(j, w) {
                mp[i + 1][j + 1] = in();
            }
        }
        ll ans = 0;
        REP(i, h) {
            REP(j, w) {
                if (mp[i + 1][j + 1] == 1) {
                    stack<pair<ll, ll>>st; st.emplace(i + 1, j + 1);
                    while (!st.empty()) {
                        auto cood = st.top(); st.pop();
                        mp[cood.first][cood.second] = 2;
                        for (ll dy = -1; dy <= 1; ++dy) {
                            for (ll dx = -1; dx <= 1; ++dx) {
                                ll y = cood.first + dy, x = cood.second + dx;
                                if (mp[y][x] == 1) {
                                    st.emplace(y, x);
                                }
                            }
                        }
                    }
                    ++ans;
                }
            }
        }
        cout << ans << endl;
    }
}

C++: #include <bits/stdc++.h>

using namespace std;

struct posi {
	int x;
	int y;
};

int main() {

	while (1) {
		int w, h;
		cin >> w >> h;

		if (w == 0 && h == 0) { return 0; }
		vector<vector<int>> mapp(h + 2, vector<int>(w + 2));
		for (int i = 1; i <= h; i++) {
			for (int j = 1; j <= w; j++) {
				cin >> mapp[i][j];
			}
		}


		vector<int> dx{ 1,1,0,-1,-1,-1,0,1 };
		vector<int> dy{ 0,1,1,1,0,-1,-1,-1 };

		vector<vector<bool>> seen(h + 2, vector<bool>(w + 2, false));
		deque<posi> todo; //考え方はスタックだけどdequeの方が使い勝手がいい


		posi s; //今いる場所
		int counter = 0;
		for (int i = 1; i <= h; i++) {
			for (int j = 1; j <= w; j++) {
				if (mapp[i][j] == 0) { continue; }
				//seen.resize(h + 2, vector<bool>(w + 2, false));

				if (seen[i][j] == false) {
					counter++;
					seen[i][j] = true;
					todo.push_back({ i,j });

					while (todo.empty() != true) {
						s = todo.back();
						bool tugiflg = false; //次があったらtrue
						for (int k = 0; k < 8; k++) {
							if (seen[s.x + dx[k]][s.y + dy[k]] != true) {
								seen[s.x + dx[k]][s.y + dy[k]] = true;
								if (mapp[s.x + dx[k]][s.y + dy[k]] == 1) {
									todo.push_back({ s.x + dx[k],s.y + dy[k] });;
									tugiflg = true;
									break;
								}
							}
						}
						if (tugiflg == false) {
							todo.pop_back();
						}
					}
				}
			}
		}

		cout << counter << endl;
	}
	return 0;

}

C++: #include <algorithm>
#include <bitset>
#include <climits>
#include <complex>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <string>
#include <tuple>
#include <utility>
#include <valarray>
#include <vector>

#define rep(i, a, n) for(int i = (a);i < (n);i++)
#define REP(i, n)    rep(i, 0, n)
#define all(e)       (e).begin(), (e).end()

#ifdef LOCAL
#define show(x) cerr<<__LINE__<<" : "<<#x<<" = "<<(x)<<endl;
#else
#define show() true
#endif

using namespace std;
using ll=long long;
template<class T> using V=vector<T>;

template<class T, class U>
void chmin(T &t, const U u) { if (t > u) t = u; }

template<class T, class U>
void chmax(T &t, const U u) { if (t < u) t = u; }

const int INF = (1 << 30) - 1;
const ll INFL = (ll) 5e15;
const int MOD = 1000000007;

using P=pair<int, int>;

class Solver {
public:
    bool solve() {
        cin >> W >> H;
        if (W == 0 && H == 0) return false;

        field.resize(W, V<int>(H));
        REP(y, H) {
            REP(x, W) {
                cin >> field[x][y];
            }
        }

        int c = 2;
        REP(y, H) {
            REP(x, W) {
                if (field[x][y] == 1) {
                    bfs(P(x, y), c);
                    ans++;
                }
            }
        }

        cout << ans << endl;
        return true;
    }

private:
    int H, W;
    V<V<int>> field;
    int ans = 0;

    int dx[8] = {0, 1, 0, -1, 1, 1, -1, -1}, dy[8] = {1, 0, -1, 0, 1, -1, -1, 1};

    void bfs(P s, int c) {
        queue<P> que;
        que.push(s);
        field[s.first][s.second] = c;
        while (que.size()) {
            P cur = que.front();
            que.pop();

            for (int i = 0; i < 8; ++i) {
                P next = {cur.first + dx[i], cur.second + dy[i]};
                if (check(next) && field[next.first][next.second] == 1) {
                    que.push(next);
                    field[next.first][next.second] = c;
                }
            }
        }
    }

    bool check(P p) {
        if (p.first < 0 || p.first >= W) return false;
        if (p.second < 0 || p.second >= H) return false;
        return true;
    }
};

int main() {

    while (Solver().solve());

    return 0;
}