use std::io; fn main() { let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let mut values = input.trim().split_whitespace().map(|s| s.parse::().unwrap()); let h = values.next().unwrap(); let w = values.next().unwrap(); let mut a = Vec::new(); for _ in 0..h { input.clear(); io::stdin().read_line(&mut input).unwrap(); a.extend(input.trim().split_whitespace().map(|s| s.parse::().unwrap())); } let mut ans = 0; let mut use_grid = vec![0; (h * w) as usize]; for i in 0..h { for j in 0..w { let index = (i * w + j) as usize; if a[index] == 1 && use_grid[index] == 0 { ans += 1; let mut q = vec![(i, j)]; use_grid[index] = 1; while !q.is_empty() { let (x, y) = q.pop().unwrap(); for (dx, dy) in &[(1, 0), (-1, 0), (0, 1), (0, -1)] { let u = x + dx; let v = y + dy; if u >= 0 && u < h && v >= 0 && v < w && a[(u * w + v) as usize] == 1 && use_grid[(u * w + v) as usize] == 0 { use_grid[(u * w + v) as usize] = 1; q.push((u, v)); } } } } } } println!("{}", ans); }