[SWEA] 1954. 달팽이 숫자
https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&problemLevel=3&contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE&problemTitle=&orderBy=RECOMMEND_COUNT&selectCodeLang=ALL&select-1=3&pageSize=10&pageIndex=1
- 문제 접근
- 얻은 꿀팁 :
- print 할 때, 리스트 앞에 * 를 붙이면 []가 출력되지 않는다
- 나는 약간 막노동 비슷하게 불었는데 알고리즘 적으로 고민해보면 훨씨 잘짜여진 패턴을 가진 코드를 짤 수 있다. 알고리즘적인 고민을 조금 더 해보고 짜는 습관을 들이자..!
- 내 코드
T=int(input())
for t in range(T):
N=int(input())
snail=[[0]*N for i in range(1,N+1)]
length=N
step="right"
number=1
row=0
col=0
while(length!=0):
if step=="right":
for _ in range(length):
snail[row][col]=number
number+=1
col+=1
length-=1
step="down"
row+=1
col-=1
elif step=="down":
for _ in range(length):
snail[row][col]=number
number+=1
row+=1
step="left"
row-=1
col-=1
elif step=="left":
for _ in range(length):
snail[row][col]=number
number+=1
col-=1
length-=1
step = "up"
row-=1
col+=1
elif step=="up":
for _ in range(length):
snail[row][col]=number
number+=1
row-=1
step="right"
row+=1
col+=1
print("#{}".format(t+1))
for i in range(N):
print(*snail[i])
- 더 멋진 코드
T = int(input())
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
for tc in range(1, T+1):
N = int(input())
snail = [[0]*N for _ in range(N)]
r, c = 0, 0
dist = 0
for n in range(1, N*N + 1):
snail[r][c] = n
r += dr[dist]
c += dc[dist]
if r < 0 or c < 0 or r >= N or c >= N or snail[r][c] != 0:
r -= dr[dist]
c -= dc[dist]
dist = (dist + 1) % 4
r += dr[dist]
c += dc[dist]
print("#{}".format(tc))
for row in snail:
print(*row)
print()