use strict; use warnings; my($h, $w) = split ' ', <>; my @map; for(<>){ push @map, [split ' ', $_]; } my @queue = (); my @vx = (0, 1, 0, -1); my @vy = (1, 0, -1, 0); my $count = 0; my($pres, $next); for my $y (0..$h-1){ for my $x (0..$w-1){ if($map[$y][$x] == 1){ $map[$y][$x]++; push @queue, {x => $x, y => $y}; while(@queue){ $pres = shift @queue; for my $i (0..3){ $next = {x => $pres->{x} + $vx[$i], y => $pres->{y} + $vy[$i]}; if(-1 < $next->{x} and $next->{x} < $w and -1 < $next->{y} and $next->{y} < $h){ if($map[$next->{y}][$next->{x}] == 1){ $map[$next->{y}][$next->{x}]++; push @queue, {x => $next->{x}, y => $next->{y}}; } } } } $count++; } } } print $count."\n";