#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

# 1 hour pl

my @matrix0=(
[0,0,0, 0,0,0],
[0,0,0, 0,0,0],
[0,0,0, 0,0,0],

[0,0,0, 0,0,0],
[0,0,0, 0,0,0],
[0,0,0, 0,0,0],
[0,0,0, 0,0,0]
);

my @matrix=(
[0,0,0, 2,0,0],
[0,0,0, 2,0,0],
[0,0,0, 2,2,0],

[0,0,0, 3,0,0],
[0,0,0, 3,0,0],
[0,0,0, 4,4,0],
[0,0,5, 5,2,0]
);

my $maxRow = $#matrix;
my $maxCol = $#{$matrix[$maxRow]};

print "[$maxCol,$maxRow]\n\n";

sub dumpMatrix()
{
	my $s="  Matrix=[\n";
	my $i=0;
	foreach my $row (@matrix)
	{
		$s.='    ['. join(',', @{$row}) . "],\n";
		if(++$i == 3){$s.="\n";}
	}
	$s.="  ];\n\n";
	print $s;
}

sub reduceMatrix()
{
	for my $r(0..$maxRow)
	{
		foreach my $c (0..$maxCol)
		{
			print ("[$r,$c]=",$matrix[$r][$c]," ");
			my $v=$matrix[$r][$c];
			if($v>0)
			{
				my $d = reduceDot($r,$c,[[$r,$c]]);
				print Dumper $d;
				killDots($d);
			}
		}
		print "\n";
	}
}

sub isInList($$$)
{
	my ($r,$c,$dot)=@_;
	my @a = @{$dot};
	foreach my $row (@a)
	{
		my @rr=@{$row};
		if($rr[0]==$r && $rr[1]==$c)
		{
			return 1;
		}
	}

	return 0;
}

sub reduceDot($$$);

sub reduceDot($$$)
{
	my ($r,$c,$dot)=@_;
	my $v = $matrix[$r][$c];
	#my @dot=[@_];

	print ("\n\nRD[$r,$c]=$v ");
	#push @dot, [@_];
	if($r > 0)
	{
		# Check up
		if($matrix[$r-1][$c]==$v)
		{
			if(!isInList($r-1,$c,$dot))
			{
				reduceDot($r-1,$c,$dot);
				push @{$dot}, [$r-1,$c];
			}
		}
	}

	if ($c < $maxCol)
	{
		# Check right
		if($matrix[$r][$c+1]==$v)
		{
			if(!isInList($r,$c+1,$dot))
			{
				reduceDot($r,$c+1,$dot);
				push @{$dot}, [$r,$c+1];
			}
		}
	}

	if ($r < $maxRow)
	{
		# Check down
		if($matrix[$r+1][$c]==$v)
		{
			if(!isInList($r+1,$c,$dot))
			{
				push @{$dot}, [$r+1,$c];
				reduceDot($r+1,$c,$dot);
			}
		}
	}

	if($c > 0)
	{
		# Check left
		if($matrix[$r][$c-1]==$v)
		{
			if(!isInList($r,$c-1,$dot))
			{
				push @{$dot}, [$r,$c-1];
				reduceDot($r,$c-1,$dot);
			}
		}
	}

	return $dot;
}

sub killDots($)
{
	my $dd = $_[0];
	my @d = @{$dd};
	my $n = $#d;
	if($n < 2){return;}

	my $cc = 0;
	my $r1 = $d[0][0];
	my $c1 = $d[0][1];

	my $v = $matrix[$r1][$c1];

	for my $cells (0 .. $n)
	{
		my $r2=$d[$cells][0];
		my $c2=$d[$cells][1];
		if( ($r2 > $r1) || (($r2 >= $r1) && ($c2 <= $c1)) )
		{
			$r1=$r2;
			$c1=$c2;
		}
		$matrix[$r2][$c2] = 0;
	}

	$matrix[ $r1 ][ $c1 ] = $v+1;

	dumpMatrix();

	return [$r1, $c1, $v+1];
}

dumpMatrix();
reduceMatrix();