@@ -76,7 +76,56 @@ def spiral_print_clockwise(a: list[list[int]]) -> None:
76
76
return
77
77
78
78
79
+ # Other Easy to understand Approach
80
+
81
+
82
+ def 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 (list (zip (* matrix ))[::- 1 ])
120
+ else :
121
+ return []
122
+
123
+
79
124
# driver code
80
125
if __name__ == "__main__" :
126
+ import doctest
127
+
128
+ doctest .testmod ()
129
+
81
130
a = [[1 , 2 , 3 , 4 ], [5 , 6 , 7 , 8 ], [9 , 10 , 11 , 12 ]]
82
131
spiral_print_clockwise (a )
0 commit comments