#![allow(unused_imports)] use std::io::{ self, Write }; use std::str::FromStr; use std::cmp::{ min, max }; use std::collections::{ BinaryHeap, VecDeque }; #[allow(unused_macros)] macro_rules! trace { ($var:expr) => { let _ = writeln!(&mut std::io::stderr(), ">>> {} = {:?}", stringify!($var), $var); }; ($($args:expr),*) => { trace!(($($args),*)) } } #[allow(unused_macros)] macro_rules! put { ($var:expr) => { let _ = writeln!(&mut std::io::stdout(), "{}", $var); }; ($var:expr, $($args:expr),*) => { let _ = write!(&mut std::io::stdout(), "{} ", $var); put!($($args),*); }; } const M: usize = 1_000_000_007; fn main() { let mut sc = Scanner::new(); let h: usize = sc.cin(); let w: usize = sc.cin(); let mut memo = vec![vec![false; w]; h]; for i in 0..h { for j in 0..w { let d: usize = sc.cin(); if d == 1 { memo[i][j] = true; } } } let mut ans = 0; for i in 0..h { for j in 0..w { if !memo[i][j] { continue } ans += 1; let mut stack = VecDeque::new(); stack.push_back((i, j)); while let Some((i, j)) = stack.pop_front() { if !memo[i][j] { continue } memo[i][j] = false; if i < h - 1 { stack.push_back((i+1, j)); } if i > 0 { stack.push_back((i-1, j)); } if j < w - 1 { stack.push_back((i, j+1)); } if j > 0 { stack.push_back((i, j-1)); } } } } put!(ans); } #[allow(dead_code)] struct Scanner { stdin: io::Stdin, buffer: VecDeque, } #[allow(dead_code)] impl Scanner { fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } } fn reserve(&mut self) { while self.buffer.len() == 0 { let mut line = String::new(); let _ = self.stdin.read_line(&mut line); for w in line.split_whitespace() { self.buffer.push_back(String::from(w)); } } } fn cin(&mut self) -> T { self.reserve(); match self.buffer.pop_front().unwrap().parse::() { Ok(a) => a, Err(_) => panic!("parse err") } } }