문제는 다음과 같습니다:
6 6 0 1 2 3 4 5 19 20 21 22 23 6 18 31 32 33 24 7 17 30 35 34 25 8 16 29 28 27 26 9 15 14 13 12 11 10
위처럼 6 6이라는 입력을 주면 6 X 6 매트릭스에 나선형 회전을 한 값을 출력해야 합니다.
풀이
#!/usr/bin/python # -*- coding: utf-8 -*- def fill_round(matrix, num, mx, my, base_x, base_y): ix = base_x iy = base_y # LR 진행 for n in range(0, mx): matrix[iy][ix] = num num = num + 1 ix = ix + 1 ix = ix - 1 mx = mx - 1 # UD 진행 iy = iy + 1 for n in range(1, my): matrix[iy][ix] = num num = num + 1 iy = iy + 1 iy = iy - 1 my = my - 1 if my < 1: return # RL 진행 ix = ix - 1 for n in range(mx - 1, -1, -1): matrix[iy][ix] = num num = num + 1 ix = ix - 1 ix = ix + 1 mx = mx - 1 if mx < 1: return # DU 진행 iy = iy - 1 for n in range(my - 1, 0, -1): matrix[iy][ix] = num num = num + 1 iy = iy - 1 return num def solution(x, y): if x < 0 or y < 0: return [[]] matrix = [[-1 for i in range(0, x)] for j in range(0, y)] num = 0 w = x h = y i = 0 while True: num = fill_round(matrix, num, w, h, i, i) i = i + 1 w = w - 2 h = h - 2 if w <= 0 or h <= 0: break return matrix matrix = solution(6, 6) print '\n'.join([' '.join(['%3u' % n for n in m]) for m in matrix]) print '' matrix = solution(9, 7) print '\n'.join([' '.join(['%3d' % n for n in m]) for m in matrix])
결과
0 1 2 3 4 5 19 20 21 22 23 6 18 31 32 33 24 7 17 30 35 34 25 8 16 29 28 27 26 9 15 14 13 12 11 10 0 1 2 3 4 5 6 7 8 27 28 29 30 31 32 33 34 9 26 47 48 49 50 51 52 35 10 25 46 59 60 61 62 53 36 11 24 45 58 57 56 55 54 37 12 23 44 43 42 41 40 39 38 13 22 21 20 19 18 17 16 15 14