Well this is a really good question for your coding practice. This is asked in many interviews to check the coding abilities of the candidiates
Lets have a 5x5 matrix as an example
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
for this answer should be
0 1 2 3 4 9 14 19 24 23 22 21 20 15 10 5 6 7 8 13 18 17 16 11 12
Time Complexity=O(n)
Space Complexity=O(1)
#include<stdio.h>
int main()
{
int n=5;
int arr[n][n];
int top=0,bottom=n,left=0,right=n;//these are the boundaries of the matrix while traversing spirally
int currX=0,currY=0;//these are the locations which are being traversed
//arr is having value 0 to 48 in row majority order
for(int k=0;k<n;k++)
for(int k1=0;k1<n;k1++)
arr[k][k1]=n*k+k1;
// this is for printing matrix value
/*for(int k=0;k<n;k++)
{
for(int k1=0;k1<n;k1++)
printf("%d\t",arr[k][k1]);
printf("\n");
}*/
while((currX!=n/2)&&(currY!=n/2))
{
//printf("%d %d %d %d\n",left,right,top,bottom);
while(currX<right)
{printf("%d\t",arr[currY][currX]);currX++;}right--;currX--;currY++;top++;
while(currY<bottom)
{printf("%d\t",arr[currY][currX]);currY++;}bottom--;currY--;currX--;
while(currX>=left)
{printf("%d\t",arr[currY][currX]);currX--;}left++;currX++;currY--;
while(currY>=top)
{printf("%d\t",arr[currY][currX]);currY--;}currY++;currX++;
}
printf("%d",arr[n/2][n/2]);
return 0;
}
Lets have a 5x5 matrix as an example
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
for this answer should be
0 1 2 3 4 9 14 19 24 23 22 21 20 15 10 5 6 7 8 13 18 17 16 11 12
Time Complexity=O(n)
Space Complexity=O(1)
#include<stdio.h>
int main()
{
int n=5;
int arr[n][n];
int top=0,bottom=n,left=0,right=n;//these are the boundaries of the matrix while traversing spirally
int currX=0,currY=0;//these are the locations which are being traversed
//arr is having value 0 to 48 in row majority order
for(int k=0;k<n;k++)
for(int k1=0;k1<n;k1++)
arr[k][k1]=n*k+k1;
// this is for printing matrix value
/*for(int k=0;k<n;k++)
{
for(int k1=0;k1<n;k1++)
printf("%d\t",arr[k][k1]);
printf("\n");
}*/
while((currX!=n/2)&&(currY!=n/2))
{
//printf("%d %d %d %d\n",left,right,top,bottom);
while(currX<right)
{printf("%d\t",arr[currY][currX]);currX++;}right--;currX--;currY++;top++;
while(currY<bottom)
{printf("%d\t",arr[currY][currX]);currY++;}bottom--;currY--;currX--;
while(currX>=left)
{printf("%d\t",arr[currY][currX]);currX--;}left++;currX++;currY--;
while(currY>=top)
{printf("%d\t",arr[currY][currX]);currY--;}currY++;currX++;
}
printf("%d",arr[n/2][n/2]);
return 0;
}
No comments:
Post a Comment