Programing/프로그래머스 오답노트
[프로그래머스] 삼각 달팽이
yooom
2023. 10. 9. 03:04
문제 설명
풀이
def cicle(n,x,y,graph,visit,cnt):
dx ,dy = [0,1,-1], [1,0,-1]
nn = -(-n//3)
for i in range(nn):
while x<n and y<n and not visit[y][x]:
visit[y][x] = True
graph[y][x] = cnt
cnt += 1
y += dy[0]
x += dx[0]
y -= 1
cnt -= 1
visit[y][x] = False
while x<n and y<n and not visit[y][x]:
visit[y][x] = True
graph[y][x] = cnt
cnt += 1
y += dy[1]
x += dx[1]
x -= 1
cnt -= 1
visit[y][x] = False
while x<n and y<n and not visit[y][x]:
visit[y][x] = True
graph[y][x] = cnt
cnt += 1
y += dy[2]
x += dx[2]
y += 1
x += 1
cnt -= 1
visit[y][x] = False
return graph
def solution(n):
x,y = 0,0
cnt = 1
graph = [[0]*n for i in range(n)]
visit = [[False]*n for i in range(n)]
graph = cicle(n,x,y,graph,visit,cnt)
arr = []
for i in graph:
for j in i:
if j:
arr.append(j)
return arr
솔직히...이렇게 푸는 거 아닌 거 같다.
1. 삼각형은 3층 씩 커질 때마다 달팽이 회전(?) 을 1번 추가로 한다. 그래서 n / 3을 하고 올림 한 값을 출력해야하므로,nn = -(-n/3) 트릭을 썼다. 회전을 nn번 시켜주자
2. graph와 visit를 만들어서 아래로, 오른쪽으로, 대각선 위로 움직이는 while 구문을 3개 써서 방문한 적이 있는 칸을 만나면 멈춘다. 이때 (y),(x),(y,x) 로 한 칸 더 움직였기 때문에, 한 칸 덜 움직인 것으로 보정한다. visit로 false로 바꿔준다.
3. graph배열에서 0이 아닌 숫자만 뽑아서 새로운 배열을 만들자.
출처
https://school.programmers.co.kr/learn/courses/30/lessons/68645
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90