MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / spiral_traversal

Function spiral_traversal

matrix/spiral_print.py:82–123  ·  view source on GitHub ↗

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

(matrix: list[list])

Source from the content-addressed store, hash-verified

80
81
82def spiral_traversal(matrix: list[list]) -> list[int]:
83 """
84 >>> spiral_traversal([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
85 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
86
87 Example:
88 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
89 Algorithm:
90 Step 1. first pop the 0 index list. (which is [1,2,3,4] and concatenate the
91 output of [step 2])
92 Step 2. Now perform matrix's Transpose operation (Change rows to column
93 and vice versa) and reverse the resultant matrix.
94 Step 3. Pass the output of [2nd step], to same recursive function till
95 base case hits.
96 Dry Run:
97 Stage 1.
98 [1, 2, 3, 4] + spiral_traversal([
99 [8, 12], [7, 11], [6, 10], [5, 9]]
100 ])
101 Stage 2.
102 [1, 2, 3, 4, 8, 12] + spiral_traversal([
103 [11, 10, 9], [7, 6, 5]
104 ])
105 Stage 3.
106 [1, 2, 3, 4, 8, 12, 11, 10, 9] + spiral_traversal([
107 [5], [6], [7]
108 ])
109 Stage 4.
110 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([
111 [5], [6], [7]
112 ])
113 Stage 5.
114 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([[6, 7]])
115 Stage 6.
116 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + spiral_traversal([])
117 """
118 if matrix:
119 return list(matrix.pop(0)) + spiral_traversal(
120 [list(row) for row in zip(*matrix)][::-1]
121 )
122 else:
123 return []
124
125
126# driver code

Callers

nothing calls this directly

Calls 1

popMethod · 0.45

Tested by

no test coverage detected