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 1 commit
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
62 changes: 62 additions & 0 deletions matrix/spiral_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"""


from typing import List


def check_matrix(matrix: list[list[int]]) -> bool:
# must be
matrix = [list(row) for row in matrix]
Expand Down Expand Up @@ -75,8 +78,67 @@ def spiral_print_clockwise(a: list[list[int]]) -> None:
print("Not a valid matrix")
return

# Other Easy to undersatnd Approach


def spiral_traversal(matrix: List[List[int]]) -> List[int]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def spiral_traversal(matrix: List[List[int]]) -> List[int]:
def spiral_traversal(matrix: list[list[int]]) -> 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([])


"""
return matrix and list(matrix.pop(0)) + spiral_traversal(list(zip(*matrix))[::-1])


# 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)