2019년 5월 29일 수요일

[leetcode] 54. Spiral Matrix

원문)
Given a matrix of m x n elements (m rows, n columns),
return all elements of the matrix in spiral order.

번역)
행렬(행 M, 열 N)주어졌을때,
나선의 모든 요소들을 반환하라.


예제)


Example 1:
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]


문제접근)

총 4개의 방향을 잡고 각 방향 별로 쪼개서 각 기능을 하도록 구현하였다.
반영 -> 체크 -> 움직임 으로 순서를 잡고 했다.


코드)



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        answer = []
        
        m = len(matrix)
        if m == 0:
            return []
        n = len(matrix[0])
        
        left = 0
        bottom = m - 1
        right = n - 1
        top = 1
        
        row = 0
        y = 0
        col = 0
        x = 1
        state = 0
        
        while len(answer) < m * n:
            # add
            answer.append(matrix[row][col])
            
            # check
            if state == 0:
                # check
                if col == right:
                    right -= 1
                    state = 1
                    # dir
                    x = 0
                    y = 1
            elif state == 1:
                # check
                if row == bottom:
                    bottom -= 1
                    state = 2
                    # dir
                    x = -1
                    y = 0
            elif state == 2:
                # check
                if col == left:
                    left += 1
                    state = 3
                    # dir
                    x = 0
                    y = -1
            else:
                # check
                if row == top:
                    top += 1
                    state = 0
                    # dir
                    x = 1
                    y = 0
                    
            # move
            row += y
            col += x
        
        return answer


댓글 없음:

댓글 쓰기