알고리즘
사각배열을 만들어 출력하는 경우
가오가이거
2022. 7. 2. 21:32
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)]와 같이 할수도있다.(파이썬의 경우..)