using System; using System.Collections.Generic; class Program { Program() { int[] A = getValues(Console.ReadLine()); int H = A[0]; int W = A[1]; int[][] field = new int[H][]; for (int i = 0; i < H; i++) { field[i] = getValues(Console.ReadLine()); } int rake = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (field[i][j] == 1) { rake++; check(field, i, j); } } } Console.WriteLine(rake); } void check(int[][] field, int sx, int sy) { Queue> queue = new Queue>(); queue.Enqueue(new Tuple(sx, sy)); field[sx][sy] = 0; while (queue.Count > 0) { var P = queue.Dequeue(); int x1 = P.Item1; int y1 = P.Item2; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (Math.Abs(i + j) != 1) { continue; } int x = x1 + i; int y = y1 + j; if (0 <= x && x < field.Length && 0 <= y && y < field[0].Length && field[x][y] == 1) { field[x][y] = 0; queue.Enqueue(new Tuple(x, y)); } } } } } static int[] getValues(string s) { string[] A = s.Split(); int[] B = new int[A.Length]; for (int i = 0; i < A.Length; i++) { B[i] = int.Parse(A[i]); } return B; } static void Main(string[] args) { new Program(); } }