From 614274a9dc996f64dd470d2029847cc229f19346 Mon Sep 17 00:00:00 2001 From: Shubham Kondekar <40213815+kondekarshubham123@users.noreply.github.com> Date: Wed, 26 Oct 2022 22:28:33 +0530 Subject: [PATCH] Update spiral_print.py (#7674) * Update spiral_print.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update matrix/spiral_print.py Co-authored-by: Caeden Perelli-Harris * Update matrix/spiral_print.py Co-authored-by: Caeden Perelli-Harris * Update matrix/spiral_print.py Co-authored-by: Caeden Perelli-Harris * Update matrix/spiral_print.py Co-authored-by: Caeden Perelli-Harris * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update spiral_print.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update spiral_print.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update spiral_print.py * Update spiral_print.py * Update spiral_print.py * Update spiral_print.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Caeden Perelli-Harris --- matrix/spiral_print.py | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/matrix/spiral_print.py b/matrix/spiral_print.py index 0cf732d60..0d0be1527 100644 --- a/matrix/spiral_print.py +++ b/matrix/spiral_print.py @@ -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)