문제 링크:leetcode.com/problems/spiral-matrix/
Spiral Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
접근 방식:
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input: matrix = [[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]
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
코드: Python3
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row = len(matrix)
col = len(matrix[0])
ans = []
if row == 0:
return ans
limit = 0
for_limit = row * col
idx_limit = 0
i = 0
j = 0
while limit < for_limit:
for k in range(j,col):
limit += 1
ans.append(matrix[i][k])
if limit == for_limit:
return ans
j = col-1
i += 1
for k in range(i,row):
limit += 1
ans.append(matrix[k][j])
if limit == for_limit:
return ans
i = row-1
j -= 1
for k in range(j,idx_limit-1,-1):
limit += 1
ans.append(matrix[i][k])
if limit == for_limit:
return ans
# i = 2
# j = 1
# tar = matrix[1][0]
i -= 1 # 1
j = idx_limit # 0
idx_limit += 1 # 1
for k in range(i,idx_limit-1,-1):
limit += 1
ans.append(matrix[k][j])
i = idx_limit
j = idx_limit
col -= 1
row -= 1
return ans
'Algorithnm > LeetCode' 카테고리의 다른 글
[LeetCode]172번 : Factorial Trailing Zeroes (0) | 2020.12.18 |
---|---|
[LeetCode] 125번 : Valid Palindrome (0) | 2020.12.13 |
최근댓글