본문 바로가기

00/algorithm

Spiral Matrix (in Python)

반응형

Problem

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


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]



Solution


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
class Solution:
 
    def spiralOrder(self, matrix):
 
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
 
        if not matrix:
            return []
 
        dr = [010-1]
        dc = [10-10]
 
        i, j, r, c = 00len(matrix), len(matrix[0])
        ans = []
 
        cur = 0
 
        for _ in range(r*c):
 
            ans.append(matrix[i][j])
            matrix[i][j] = ""
 
            nr = i + dr[cur]
            nc = j + dc[cur]
 
            # 벽에 부딪히면 방향 변경
            if matrix[(nr)%r][(nc)%c] == "":
                cur = (cur+1)%4
 
            # 다음 값 지정
            i = i + dr[cur]
            j = j + dc[cur]
 
        return ans
cs



이건 삼성 코테 단골 문제 유형인데 왜 이렇게 시간이 걸렸을까..

연습이 너무 부족해.. 연습을 하자...연습..! 할수있다!


Source

https://leetcode.com/problems/spiral-matrix/

반응형

'0 > algorithm' 카테고리의 다른 글

Rotate Image (in Python)  (0) 2019.01.23
Permutations (in Python)  (0) 2019.01.23
Find First and Last Position of Element in Sorted Array (in Python)  (0) 2019.01.22
Next Permutation (in Python)  (0) 2019.01.21
Swap Nodes in Pairs (in Python)  (0) 2019.01.21