본문 바로가기
알고리즘

[BOJ / 1913 / Python] 달팽이

by 치우치지않는 2023. 9. 20.

[ 문제 ]

https://www.acmicpc.net/problem/1913

[ 난이도 ]

실버3

[ 필요 개념 ]

2차원 배열에 대한 지식 정도..? 딱히 없는 듯 

[ 풀이 ]

처음에는 상,하,좌,우가 몇 번을 주기로 반복되는지 여부로 생각했는데, 이걸 배열로 구현해야 한다고 생각하니 막막 >> 구현이 목적이고, 출력이 목적이므로, 적당히 규칙을 발견한 뒤에는 코드를 대략적으로 짜고 디버깅을 반복하는 것이 좋은 방법이라 생각 >> 대각선의 성질을 이용해서 문제 풀이 완료. (과정에서 배열에 직접 수를 넣으면서 코드로 예를 들어보는 것이 도움이 되었고, 로그를 찍으며 디버깅하는 것이 재미있었음. 또 웬만하면 변수로 써야 하는 부분에 상수를 써서 테스트하지 말고, 바로 변수를 넣는 것이 나중에 쓸데없는 디버깅을 줄이는 시간임을 알게됨. + 디버깅할 때는 콘솔을 부분만 보는 것이 아니라, 처음부터 끝줄까지 보고 무엇이 문제일지 생각해야 함.)

[ 소스코드 ]

rowColNum = int(input())
wannaFindLocationNum = int(input())

table = [[0 for j in range(rowColNum)] for i in range(rowColNum)]

# make some examples to understand problem
# table[2][2] = 1
# #up, change the line

# table[1][2] = 2
# #right
# table[1][3] = 3
# #down
# table[2][3] = 4
# #down
# table[3][3] = 5
# #left
# table[3][2] = 6
# #left
# table[3][1] = 7
# #up
# table[2][1] = 8
# #up
# table[1][1] = 9

# #up, change the line
# table[0][1] = 10 
# table[0][2] = 11
# table[0][3] = 12
# table[0][4] = 13 

#start value 
X = rowColNum // 2 
Y = rowColNum // 2 

# #found number location 
foundX = 0
foundY = 0

for i in range(rowColNum * rowColNum) :
  #markup
  table[X][Y] = i+1
  if i+1 == wannaFindLocationNum :
    foundX = X
    foundY = Y
  #change X,Y for next Step 
  #change the line
  if X == Y and X <= rowColNum // 2 and Y <= rowColNum // 2 :
    # print('X is ....' + str(X))
    # print('Y is ....' + str(Y))
    X = X - 1
    # print('change the line')
  #move to right
  elif X < Y and X + Y < rowColNum-1 :
    # print('X is ....' + str(X))
    # print('Y is ....' + str(Y))
    Y = Y + 1 
    # print('move to right')
  #move to down
  elif X < Y and X + Y >= rowColNum-1 :
    # print('X is ....' + str(X))
    # print('Y is ....' + str(Y))
    X = X + 1
    # print('move to down')
  #move to left
  elif X >= Y and X + Y > rowColNum-1 :
    # print('X is ....' + str(X))
    # print('Y is ....' + str(Y))
    Y = Y - 1
    # print('move to left')
  #move to up
  elif X > Y and X + Y <= rowColNum-1 :
    # print('X is ....' + str(X))
    # print('Y is ....' + str(Y))
    X = X - 1
    # print('move to up')


for i in table :
  for j in i :
    print(j, end=' ')
  print()

print(str(foundX + 1) + ' ' + str(foundY + 1))

댓글