From 33568af8c0ee8c09c34027f0742a858998654f87 Mon Sep 17 00:00:00 2001 From: Sitesh Pattanaik Date: Thu, 31 Oct 2019 15:17:24 +0530 Subject: [PATCH 1/2] Added new code in Arrays --- Arrays/Spiral_Matrix.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Arrays/Spiral_Matrix.py diff --git a/Arrays/Spiral_Matrix.py b/Arrays/Spiral_Matrix.py new file mode 100644 index 0000000..cb5d10f --- /dev/null +++ b/Arrays/Spiral_Matrix.py @@ -0,0 +1,26 @@ +# Complexity Analysis + +# Time Complexity: O(N)O(N), where NN is the total number of elements in the input matrix. We add every element in the matrix to our final answer. + +# Space Complexity: O(N)O(N), the information stored in seen and in ans. + + +class Solution(object): + def spiralOrder(self, matrix): + if not matrix: return [] + R, C = len(matrix), len(matrix[0]) + seen = [[False] * C for _ in matrix] + ans = [] + dr = [0, 1, 0, -1] + dc = [1, 0, -1, 0] + r = c = di = 0 + for _ in range(R * C): + ans.append(matrix[r][c]) + seen[r][c] = True + cr, cc = r + dr[di], c + dc[di] + if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]: + r, c = cr, cc + else: + di = (di + 1) % 4 + r, c = r + dr[di], c + dc[di] + return ans From e1a6ec143089dbeff9b4ccfbeacdbbb6944505ed Mon Sep 17 00:00:00 2001 From: Sitesh Pattanaik Date: Thu, 31 Oct 2019 16:02:49 +0530 Subject: [PATCH 2/2] Added problem statement --- Arrays/Spiral_Matrix.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Arrays/Spiral_Matrix.py b/Arrays/Spiral_Matrix.py index cb5d10f..b0798fd 100644 --- a/Arrays/Spiral_Matrix.py +++ b/Arrays/Spiral_Matrix.py @@ -1,3 +1,16 @@ +''' + Given a 2D array, print it in spiral form. See the following examples. + +Input: + 1 2 3 4 + 5 6 7 8 + 9 10 11 12 + 13 14 15 16 +Output: +1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 + +''' + # Complexity Analysis # Time Complexity: O(N)O(N), where NN is the total number of elements in the input matrix. We add every element in the matrix to our final answer.