I am still a beginner and I was trying out this Leetcode problem regarding spiral matrices. I ran the following code and it worked on my IDE but on Leetcode ended prematurely after just one iteration.
def spiralOrder(matrix):
new_matrix = []
top_row_count = 0
left_col_count = 0
bottom_row_count = 0
right_col_count = 0
while True:
for i in range(left_col_count, len(matrix[0]) - right_col_count):
new_matrix.append(matrix[top_row_count][i])
top_row_count += 1
if top_row_count >= len(matrix[0]) / 2:
break
for i in range(top_row_count, len(matrix) - bottom_row_count - 1):
new_matrix.append(matrix[i][len(matrix[0]) - right_col_count - 1])
for i in reversed(range(left_col_count, len(matrix[0]) - right_col_count)):
new_matrix.append(matrix[len(matrix) - bottom_row_count - 1][i])
right_col_count += 1
bottom_row_count += 1
if right_col_count >= len(matrix) / 2 or bottom_row_count >= len(matrix[0]) / 2:
break
for i in list(reversed(range(top_row_count, len(matrix) - bottom_row_count))):
new_matrix.append(matrix[i][left_col_count])
left_col_count += 1
if left_col_count >= len(matrix) / 2:
break
return(new_matrix)
For the testcase, matrix = [[1,2,3],[4,5,6],[7,8,9]], the expected response of [1,2,3,6,9,8,7,4,5] is not achieved and [1,2,3] is achieved instead. I am not sure why
New contributor
A. A. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.