Notice
Recent Posts
Recent Comments
Link
관리 메뉴

Star_project

n 소용돌이 수 | 달팽이 문제 본문

코딩테스트/Python

n 소용돌이 수 | 달팽이 문제

star빛 2022. 6. 9. 13:06

 

[COS PRO 1급] 1회 5번 - n 소용돌이 수 | 달팽이 문제

 

#You may use import as below.
#import math

def solution(n):
    # Write code here.
  a=[ [0]*n for _ in range(n)]
  dir=0
  loop=n
  r, c=0, -1
  num=0
  dr=[0, 1, 0 ,-1]
  dc=[1, 0, -1, 0]
  while num<n*n:
    for _ in range(loop):
      r+=dr[dir]
      c+=dc[dir]
      num+=1
      a[r][c]=num
    dir=(dir+1)%4
    if dir%2 : loop-=1
  answer=0
  for x in range(n):
    answer+=a[x][x]
  return answer


#The following is code to output testcase.
n1 = 3
ret1 = solution(n1)

#Press Run button to receive output. 
print("Solution: return value of the function is", ret1, ".")
    
n2 = 2
ret2 = solution(n2)

#Press Run button to receive output. 
print("Solution: return value of the function is", ret2, ".")
Solution: return value of the function is 15 .
Solution: return value of the function is 4 .

참고 영상: https://www.youtube.com/watch?v=3fVqkLwgoPA&list=PLnp1rUgG4UVbZ9t778bKYSH9G5UhllEIE&index=6