Created
November 7, 2022 09:32
-
-
Save sang-d/77df4ad9470616461f39da65f5bbfd34 to your computer and use it in GitHub Desktop.
spiral print
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Print a matrix m x n following sprial-in clockwise direction from top left | |
Example: | |
matrix: | |
1 2 3 4 5 6 7 8 | |
9 0 1 2 3 4 5 6 | |
7 8 9 0 1 2 3 4 | |
5 6 7 8 9 0 1 2 | |
sprial print: | |
1 2 3 4 5 6 7 8 6 4 2 1 0 9 8 7 6 5 7 9 0 1 2 3 4 5 3 2 1 0 9 8 | |
""" | |
def print_ltr(matrix, r): | |
r.extend(matrix[0]) | |
return matrix[1:] | |
def print_ttb(matrix, r): | |
r.extend([row[-1] for row in matrix]) | |
return [row[:len(matrix[0])-1] for row in matrix] | |
def print_rtl(matrix, r): | |
r.extend(matrix[-1][::-1]) | |
return matrix[:len(matrix)-1] | |
def print_btt(matrix, r): | |
r.extend([row[0] for row in matrix[::-1]]) | |
return [row[1:] for row in matrix] | |
def sprial_print(matrix): | |
direction = 0 | |
result = [] | |
while matrix: | |
if direction == 0: | |
matrix = print_ltr(matrix, result) | |
if direction == 1: | |
matrix = print_ttb(matrix, result) | |
if direction == 2: | |
matrix = print_rtl(matrix, result) | |
if direction == 3: | |
matrix = print_btt(matrix, result) | |
direction = (direction + 1) % 4 | |
print(result) | |
matrix = [ | |
[1, 2, 3, 4, 5, 6, 7, 8], | |
[9, 0, 1, 2, 3, 4, 5, 6], | |
[7, 8, 9, 0, 1, 2, 3, 4], | |
[5, 6, 7, 8, 9, 0, 1, 2] | |
] | |
sprial_print(matrix) | |
# [1, 2, 3, 4, 5, 6, 7, 8, 6, 4, 2, 1, 0, 9, 8, 7, 6, 5, 7, 9, 0, 1, 2, 3, 4, 5, 3, 2, 1, 0, 9, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment