Traverse Square Matrix - Spiral Clockwise
Coding Problem Keys
Traverse Square Matrix - Spiral Clockwise
Problem Statement
A square matrix of size N*N is provided. The program must traverse the matrix spirally and print the elements in a single line.
Boundary Condition(s)
2 <= N <= 100
0 <= C(i, j) <= 9999
Input Format
The first line contains N.
Next N lines, contain N column values C(i, j) each separated by a space.
Output Format
The first line contains N*N values separated by a space.
Example Input/Output 1
Input
2
1 2
3 4
Output
1 2 4 3
Example Input/Output 2
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Example Input/Output 3
Input
5
2 7 7 7 9
10 2 4 2 10
2 9 4 9 2
7 15 10 14 10
12 9 15 12 2
Output
2 7 7 7 9 10 2 10 2 12 15 9 12 7 2 10 2 4 2 9 14 10 15 9 4
Note: Max Execution Time Limit: 5000 millisecs
Solution
Programming Language: Python 3 Language
n=int(input())
l=[input().split() for i in range(n)]
m=0;i=0;j=0
while(n!=n//2):
while(j<n):
print(l[i][j],end=" ")
j+=1
i+=1;j-=1
while(i<n):
print(l[i][j],end=" ")
i+=1
i-=1
while(j>m):
j-=1
print(l[i][j],end=" ")
m+=1
while(i>m):
i-=1
print(l[i][j],end=" ")
n-=1;j+=1
# Published By PKJCODERS
(Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.)
Comments