반응형
문제 설명: 양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.
제한사항
- 1 ≤ n ≤ 30
문제 해결
def solution(n):
answer = [[0] * n for _ in range(n)]
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
x, y, direction = 0, 0, 0
for cnt in range(1, n**2 + 1):
answer[x][y] = cnt
nx, ny = x + dx[direction], y + dy[direction]
if not (0 <= nx < n and 0 <= ny < n) or answer[nx][ny] != 0: # () 계산후 not을 수행, 그 다음 or 수행
direction = (direction + 1) % 4
nx, ny = x + dx[direction], y + dy[direction]
x, y = nx, ny
return answer
반응형
'코딩_Python(Level.0)' 카테고리의 다른 글
| [Level.0] 옹알이(1) (0) | 2026.03.25 |
|---|---|
| [Level.0] 평행 (0) | 2026.03.25 |
| [Level.0] 겹치는 선분의 길이 (0) | 2026.03.25 |
| [Level.0] 주사위 게임(3) (0) | 2026.03.25 |
| [Level.0] 안전지대 (0) | 2026.03.25 |