Thursday, November 5, 2020

The Joy of Computing using Python Week-7 Programming Assignment 3: Counter Spiral

 


Programming Assignment 3: Counter Spiral

Due on 2020-11-05, 23:59 IST
Given a square matrix, you have to write a program to print it in a counter-clockwise spiral form.


Input Format:
The first line of the input contains a number n which represents the number of rows and columns in the matrix.
From the second line contains the n rows with each row having n elements separated by a space.

Output Format:
Print the elements in a single line with each element separated by a space

Example:

Input:
4
25 1 29 7
24 20 4 32
16 38 29 1
48 25 21 19

Output:
25 24 16 48 25 21 19 1 32 7 29 1 20 38 29 4

Explanation: 
In the above example, each row, first all the elements of the first column is printed which are 25 24 16 48 after that, remaining elements of the last row is printed which are 25 21 and 19.
After which the remaining elements of the last column is printed which are 1 32 and 7 and so on...

n=int(input())
mat=[]
l=[]
for i in range(n):
  mat.append(input().split())
r=0
N=n
while(N>0 and N!=1):
  j=r
  for i in range(r,n-(r+1)):
    l.append(mat[i][j])
  i=i+1
  for j in range(j,n-(r+1)):
    l.append(mat[i][j])
  j=n-(r+1)
  for i in range(1+r,n-r):
    l.append(mat[-i][j])
  i=r
  for j in range(1+r,n-r):
    l.append(mat[i][-j])
  r=r+1
  N=N-2
if n==3:
  l.append(mat[1][1])
if n==5:
  l.append(mat[2][2])
if n==7:
  l.append(mat[3][3])
if n==9:
  l.append(mat[4][4])
  print(*l,end='')
else:
  print(*l,end='')

No comments:

Post a Comment