Create return_matrix_in_spiral.py

This commit is contained in:
marina 2023-07-31 17:36:30 -07:00 committed by GitHub
parent b467dca561
commit 8c631c5cd0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
def spiral_order(matrix):
result = []
rows, cols = len(matrix), len(matrix[0])
up = left = 0
right = cols - 1
down = rows - 1
while len(result) < rows * cols:
for col in range(left, right + 1):
result.append(matrix[up][col])
for row in range(up + 1, down + 1):
result.append(matrix[row][right])
if up != down:
for col in range(right - 1, left - 1, -1):
result.append(matrix[down][col])
if left != right:
for row in range(down - 1, up, -1):
result.append(matrix[row][left])
left += 1
right -= 1
up += 1
down -= 1
return result