PROBLEM LINK:
Practice
Contest
Author: Ayush Nagal
DIFFICULTY:
EASY-MEDIUM
PREREQUISITES:
2d-Array
PROBLEM:
Given N, and an N * N matrix, print the integers of the matrix (in a space separated format) in the spiral order, clockwise starting from the top left corner.
EXPLANATION:
We need 4 for loops for solving this problem. The first one for printing the elements from left to right, second one for top to bottom, third one for right to left and the fourth one for bottom to top.
int m=n;
int r=0;
while(r<=(n/2))
{
for(int i=r;i<m;i++)//From left to right
printf("%d ",a[r][i]);
for(int i=r+1;i<m;i++)//From top to bottom
printf("%d ",a[i][m-1]);
for(int i=m-2;i>=r;i--)//From right to left
printf("%d ",a[m-1][i]);
for(int i=m-2;i>r;i--)//From bottom to top
printf("%d ",a[i][r]);
r++;
m--;
}
AUTHOR’S SOLUTION:
Author’s solution can be found here.