import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) ############################## class UnionFind: def __init__(self, N): self.rank = [0] * N self.parent = [i for i in range(N)] self.n = N def find(self, x): if self.parent[x] == x: return x else: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def unite(self, x, y): x = self.find(x) y = self.find(y) if (x == y): return if (self.rank[x] < self.rank[y]): self.parent[x] = y else: self.parent[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def same(self, x, y): return self.find(x) == self.find(y) def delete(self, idx): self.parent[idx] = -1 H, W = map(int, input().split()) uf = UnionFind(H*W+1) pond = [ [0 for _ in range(W)] for _ in range(H) ] idxs = [ [0 for _ in range(W)] for _ in range(H) ] idx = 0 for i in range(H): A = list(map(int, input().split())) tmp_idx = [] tmp = [] for j in range(len(A)): tmp.append(A[j]) tmp_idx.append(idx) idx += 1 pond[i] = tmp idxs[i] = tmp_idx #print(pond) #print(idxs) #exit() for h in range(H): for w in range(W): if pond[h][w] == 0: # 対象外のは -1 を突っ込んで壊す uf.delete(idxs[h][w]) continue if h > 0: if pond[h-1][w] == 1: uf.unite(idxs[h-1][w], idxs[h][w]) if w > 0: if pond[h][w-1] == 1: uf.unite(idxs[h][w-1], idxs[h][w]) if w < W-1: if pond[h][w+1] == 1: uf.unite(idxs[h][w+1], idxs[h][w]) if h < H-1: if pond[h+1][w] == 1: uf.unite(idxs[h+1][w], idxs[h][w]) #print(uf.parent) count = 0 for i in range(H*W): if uf.parent == -1: continue if uf.find(i) == i: count += 1 if count == H*W: print(0 if pond[0][0] == 0 else 1) else: print(count)