Problem:
Given a positive integer(n), print square matrix(n x n) in anticlockwise direction.
Check sample input/output for better understanding
Check sample input/output for better understanding
Input Format:
N=a positive integer
Output Format:
square matrix in anti-clockwise direction
Constraints:
None
None
Sample Input
4
Sample Output:
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
2 13 16 9
3 14 15 8
4 5 6 7
Explanations:
Solution:
use warnings;
my $n=<STDIN>;
my $m=$n;
my @arr=();
my $ans=1;
my $row=0;
my $col=$n-1;
my $i=0;
my $j=0;
while($n>=1)
{
for($i=$row;$i<=$col;$i++)
{
$arr[$i][$row]=$ans;
$ans++;
}
for($i=$row+1;$i<=$col;$i++)
{
$arr[$col][$i]=$ans;
$ans++;
}
for($i=$col-1;$i>=$row;$i--)
{
$arr[$i][$col]=$ans;
$ans++;
}
for($i=$col-1;$i>=$row+1;$i--)
{
$arr[$row][$i]=$ans;
$ans++;
}
$n=$n-2;
$row=$row+1;
$col=$col-1;
}
for($i=0;$i<$m;$i++)
{
for($j=0;$j<$m;$j++)
{
print "$arr[$i][$j] ";
}
print "\n";
}
Tips:
On completing 1 full anticlockwise cycle, the dimension of matrix will change by 2, so i used $n=$n-2
No comments:
Post a Comment