From 3a451165d6858a409a2e29338f39c7c6d63c210c Mon Sep 17 00:00:00 2001 From: mhrooz Date: Sat, 8 Jun 2024 17:13:50 +0200 Subject: [PATCH] 54 array ops --- 54-240608-pass/main.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 54-240608-pass/main.py diff --git a/54-240608-pass/main.py b/54-240608-pass/main.py new file mode 100644 index 0000000..ef4ec18 --- /dev/null +++ b/54-240608-pass/main.py @@ -0,0 +1,32 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + d = [(0,1),(1,0),(0,-1),(-1,0)] + cur_d = 0 + width = len(matrix[0]) + height = len(matrix) + m, n = width, height - 1 + cur_m, cur_n = 0,0 + cur_p = (0,0) + rlt = [] + for i in range(width * height): + # print(cur_p, m, n, cur_m, cur_n) + row = cur_p[0] + col = cur_p[1] + rlt.append(matrix[row][col]) + if cur_d % 2 == 0: + cur_m += 1 + if cur_m == m: + m -= 1 + cur_d += 1 + cur_d %= 4 + cur_m = 0 + else: + cur_n += 1 + if cur_n == n: + n -= 1 + cur_d += 1 + cur_d %= 4 + cur_n = 0 + cur_p = (row + d[cur_d][0], col+d[cur_d][1]) + + return rlt \ No newline at end of file