Skip to content

Update spiral_print.py #7674

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Oct 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions matrix/spiral_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,56 @@ def spiral_print_clockwise(a: list[list[int]]) -> None:
return


# Other Easy to understand Approach


def spiral_traversal(matrix: list[list]) -> list[int]:
"""
>>> spiral_traversal([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Example:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Algorithm:
Step 1. first pop the 0 index list. (which is [1,2,3,4] and concatenate the
output of [step 2])
Step 2. Now perform matrix’s Transpose operation (Change rows to column
and vice versa) and reverse the resultant matrix.
Step 3. Pass the output of [2nd step], to same recursive function till
base case hits.
Dry Run:
Stage 1.
[1, 2, 3, 4] + spiral_traversal([
[8, 12], [7, 11], [6, 10], [5, 9]]
])
Stage 2.
[1, 2, 3, 4, 8, 12] + spiral_traversal([
[11, 10, 9], [7, 6, 5]
])
Stage 3.
[1, 2, 3, 4, 8, 12, 11, 10, 9] + spiral_traversal([
[5], [6], [7]
])
Stage 4.
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([
[5], [6], [7]
])
Stage 5.
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([[6, 7]])
Stage 6.
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + spiral_traversal([])
"""
if matrix:
return list(matrix.pop(0)) + spiral_traversal(list(zip(*matrix))[::-1])
else:
return []


# driver code
if __name__ == "__main__":
import doctest

doctest.testmod()

a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
spiral_print_clockwise(a)