Spiral Print Matrix
Python
Medium
2 views
Problem Description
Read r and c and a matrix. Output elements in spiral order.
Input Format
First line r c. Next r lines c ints.
Output Format
One line spiral order.
Sample Test Case
Input:
3 3
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
r,c=map(int,lines[0].split())
mat=[]
for i in range(r):
mat.append(list(map(int,(lines[1+i] if 1+i<len(lines) else '').split()[:c])))
top=0
bottom=r-1
left=0
right=c-1
out=[]
while top<=bottom and left<=right:
for j in range(left,right+1):
out.append(str(mat[top][j]))
top+=1
for i in range(top,bottom+1):
out.append(str(mat[i][right]))
right-=1
if top<=bottom:
for j in range(right,left-1,-1):
out.append(str(mat[bottom][j]))
bottom-=1
if left<=right:
for i in range(bottom,top-1,-1):
out.append(str(mat[i][left]))
left+=1
sys.stdout.write(' '.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!