using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static void Main() { var HW = ReadLine().Split().Select(int.Parse).ToArray(); var H = HW[0]; var W = HW[1]; var map = new int[H, W]; var zero = 0; for (int i = 0; i < H; i++) { var line = ReadLine().Split().Select(int.Parse).ToArray(); for (int j = 0; j < W; j++) { map[i, j] = line[j]; if (line[j] == 0) zero++; } } var uf = new UnionFind(H * W); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (map[i, j] == 0) continue; var m = i * W + j; if (j != W - 1 && map[i, j + 1] == 1) uf.Unite(m, m + 1); if (i != H - 1 && map[i + 1, j] == 1) uf.Unite(m, m + W); } } WriteLine(uf.count - zero); } } class UnionFind { public int count; int[] parent; int[] rank; public UnionFind(int size) { var b = new int[size]; for (int i = 0; i < b.Length; i++) { b[i] = i; } parent = b; rank = new int[size]; count = size; } int Root(int x) => parent[x] == x ? x : parent[x] = Root(parent[x]); public bool Same(int x, int y) => Root(x) == Root(y); public void Unite(int x, int y) { x = Root(x); y = Root(y); if (x == y) return; count--; if (rank[x] < rank[y]) { parent[x] = y; } else { parent[y] = x; if (rank[x] == rank[y]) rank[x]++; } } }