7 September 2014

Quiz 23: Find all cavities within given blocks

Problem:
We have N x N Blocks. Each block have a depth ranging from 0-9 mts. Now a block is called a "Cavity" if it is not in corner row or column and all other neighboring blocks have less depth. Neighbor is any block which share a common side.
Find all such cavities

Input Format:
N
Followed by N lines with depth of each block

Output Format:
Replace all cavities by X

Constraints:
none

Sample Input
7
4111114
1191111
3111103
1111541
1516132
1111111
6666666

Sample Output:
4111114
11X1111
3111103
1111X41
1X1X132
1111111
6666666

Explanations:-
line 2, 3rd element 9 is greater than all neighbors, so it is a cavity and replaced by X

Solution:

chomp(\$n=<STDIN>);
\$str1;
for(\$i=0;\$i<\$n;\$i++)
{
chomp(\$s=<STDIN>);
\$str1=\$str1.\$s;
}
@arr=split("",\$str1);
\$len=@arr;
for(\$i=\$n;\$i<\$len-\$n-1;\$i++)
{
if(\$i%\$n==0 or \$i%\$n==\$n-1)
{
next;
}
elsif(\$arr[\$i]>\$arr[\$i+1] and \$arr[\$i]>\$arr[\$i-1] and \$arr[\$i]>\$arr[\$i-\$n] and \$arr[\$i]>\$arr[\$i+\$n])
{
if(\$arr[\$i-\$n] eq "X" or \$arr[\$i-1] eq "X")
{
}
else
{
\$arr[\$i] = X;
}
}
}
for(\$i=1;\$i<\$len+1;\$i++)
{
print "\$arr[\$i-1]";
if(\$i%\$n == 0)
{
print "\n";
}
}

Tips:
Make a single array and then check if element is cavity