def solution(n):
array = [[0 for j in range(n)] for i in range(n)] # 1
result = []
startRow, endRow = 0, len(array) - 1
startCol, endCol = 0, len(array[0]) - 1
count=0
while startRow <= endRow and startCol <= endCol:
for col in range(startCol, endCol + 1):
count += 1
array[startRow][col]=count
result.append(array[startRow][col])
for row in range(startRow + 1, endRow + 1):
count += 1
array[row][endCol]=count
result.append(array[row][endCol])
for col in reversed(range(startCol, endCol)):
if startRow == endRow:
break
count += 1
array[endRow][col] = count
result.append(array[endRow][col])
for row in reversed(range(startRow + 1, endRow)):
if startCol == endCol:
break
count += 1
array[row][startCol] = count
result.append(array[row][startCol])
startRow += 1
endRow -= 1
startCol += 1
endCol -= 1
return result
(출처: 프로그래머스)
- 2차원 공간에서의 이동은 방향벡터를 이용한 문제가 많이 나온다고 함.
# 동, 북, 서, 남
dx=[0, -1, 0, 1],
dy=[1, 0, -1, 0] #와 같이..
또는 strps=[(0,1), (-1,0), (0,-1), (1,0)]와 같이 할수도있다.(파이썬의 경우..)
'알고리즘' 카테고리의 다른 글
소수구하기/ 소수판별 (0) | 2022.07.02 |
---|---|
우선순위큐(최소힙) (0) | 2022.07.02 |
커스텀 정렬(파이썬) (0) | 2022.07.02 |
1이 될때까지. (0) | 2022.07.02 |
DFS / BFS (0) | 2022.06.29 |