using System; using System.Collections.Generic; using System.Linq; using static Input; public class Prog { private const int INF = 1000000007; private const long INFINITY = 9223372036854775807; private struct Pair { public int x, y; } private static int[] dx = { 1, 0, -1, 0 }; private static int[] dy = { 0, -1, 0, 1 }; public static void Main() { int H = NextInt(); int W = NextInt(); int[,] map = new int[H, W]; for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) map[i, j] = NextInt(); UnionFind UF = new UnionFind(H * W); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) { if (map[i, j] != 1) continue; for (int d = 0; d < 4; d++) { int xx = j + dx[d]; int yy = i + dy[d]; if (xx < 0 || W <= xx || yy < 0 || H <= yy) continue; if (map[yy, xx] == 1) UF.Unite(i * W + j, yy * W + xx); } } HashSet pos = new HashSet(); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) { if (map[i, j] == 0) { continue; } int k = i * W + j; int r = UF.Root(k); //if (!pos.Contains(r)) pos.Add(r); } Console.WriteLine(pos.Count()); } } public class UnionFind { public List parent = new List(); public UnionFind(int N) { for (int i = 0; i < N; i++) parent.Add(i); } public int Root(int a) { if (parent[a] == a) return a; else return parent[a] = Root(parent[a]); } public void Unite(int a, int b) { a = Root(a); b = Root(b); if (a == b) return; parent[a] = parent[b]; } public bool Same(int a, int b) { return (Root(a) == Root(b)); } } public class Input { private static Queue q = new Queue(); private static void Confirm() { if (q.Count == 0) foreach (var s in Console.ReadLine().Split(' ')) q.Enqueue(s); } public static int NextInt() { Confirm(); return int.Parse(q.Dequeue()); } public static long NextLong() { Confirm(); return long.Parse(q.Dequeue()); } public static char NextChar() { Confirm(); return char.Parse(q.Dequeue()); } public static string NextString() { Confirm(); return q.Dequeue(); } public static double NextDouble() { Confirm(); return double.Parse(q.Dequeue()); } public static int[] LineInt() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } public static long[] LineLong() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } public static string[] LineString() { return Console.ReadLine().Split(' ').ToArray(); } public static double[] LineDouble() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); } }