Scribbling

LeetCode: 54. Spiral Matrix 본문

Computer Science/Coding Test

LeetCode: 54. Spiral Matrix

focalpoint 2021. 9. 17. 19:16

Recursion solution:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        self.ret = []
        self.helper(matrix, 0, 0, len(matrix), len(matrix[0]))
        return self.ret
        
    def helper(self, matrix, y, x, m, n):
        if m > 0:
            for i in range(n):
                self.ret.append(matrix[y][x])
                x += 1
            x -= 1
            m -= 1
        if n > 0 :
            for i in range(m):
                y += 1
                self.ret.append(matrix[y][x])
            n -= 1
        if m > 0:
            for i in range(n):
                x -= 1
                self.ret.append(matrix[y][x])
            m -= 1
        if n > 0:
            for i in range(m):
                y -= 1
                self.ret.append(matrix[y][x])
            n -= 1
        if m > 0 and n > 0:
            self.helper(matrix, y, x+1, m, n)

 

Somewhat more concise solution.

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ret = []
        rows, columns = len(matrix), len(matrix[0])
        up, left = 0, 0
        right, down = columns - 1, rows - 1
        while len(ret) < rows * columns:
            for x in range(left, right+1):
                ret.append(matrix[up][x])
            
            for y in range(up+1, down+1):
                ret.append(matrix[y][right])
            
            if up != down:
                for x in range(right-1, left-1, -1):
                    ret.append(matrix[down][x])
                    
            if left != right:
                for y in range(down-1, up, -1):
                    ret.append(matrix[y][left])
            
            up += 1
            left += 1
            right -= 1
            down -= 1
        
        return ret

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 57. Insert Interval  (0) 2021.09.24
LeetCode: 56. Merge Intervals  (0) 2021.09.23
LeetCode: 55. Jump Game  (0) 2021.09.15
LeetCode: 52. N-Queens II  (0) 2021.09.15
LeetCode: 51. N-Queens  (0) 2021.09.14