일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- attribute
- LeetCode
- Substring with Concatenation of All Words
- Regular Expression
- 109. Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Python Code
- t1
- Class
- 파이썬
- DWG
- Generator
- shiba
- iterator
- 시바견
- data science
- 밴픽
- kaggle
- 운영체제
- concurrency
- 315. Count of Smaller Numbers After Self
- Python
- Decorator
- Protocol
- 프로그래머스
- 43. Multiply Strings
- 30. Substring with Concatenation of All Words
- 715. Range Module
- Python Implementation
- 컴퓨터의 구조
Archives
- Today
- Total
Scribbling
LeetCode: 54. Spiral Matrix 본문
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 |