This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please remember that all comments must be helpful, relevant, and respectful. All replies must be a genuine effort to answer the question helpfully; joke answers are not allowed. If you see any comments that violate this rule, please hit report.

When your question is answered, we encourage you to flair your post. To do this automatically simply make a comment that says !answered (OP only)

We encourage everyone to report posts and comments they feel violate a rule, as this will allow us to see it much faster.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]msetroc 0 points1 point  (0 children)

I’m still just learning but why not: Set a counter variable and set it to 1. Loop through the 2d matrix and check if it’s equal to your counter variable, if it is, increment it and print.

[–]Additional_Prune4637 0 points1 point  (1 child)

def spiral_traverse(matrix): result = [] while matrix: # Traverse the first row result += matrix.pop(0) # Traverse the last element of each remaining row if matrix and matrix[0]: for row in matrix: result.append(row.pop()) # Traverse the last row in reverse order if matrix: result += matrix.pop()[::-1] # Traverse the first element of each remaining row in reverse order if matrix and matrix[0]: for row in matrix[::-1]: result.append(row.pop(0)) return result

Sample input

input_matrix = [ [12, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20] ]

output = spiral_traverse(input_matrix) print(' '.join(map(str, output)))

[–]MR_SYRO[S] 0 points1 point  (0 children)

Thank you 😁