달팽이

홍범선·2023년 11월 18일
0

알고리즘

목록 보기
29/59

문제

풀이

배열을 만들기 위해서 달팽이를 거꾸로 생각을 했다.
(0, 0, 25) ~ (4, 0, 21) => 아래방향
(4, 1, 20) ~ (4, 4, 17) => 오른쪽방향
(3, 4, 16) ~ (0, 4, 13) => 위쪽방향
(0, 3, 12) ~ (0, 1, 10) => 왼쪽방향

이렇게 5//2 + 1 = 3만큼 하면 배열을 만들 수 있다.

for test_case in range(1):
    n = int(sys.stdin.readline().rstrip())
    m = int(sys.stdin.readline().rstrip())

    graph = [[0 for i in range(n)] for j in range(n)]

    num = n*n
    length = n // 2
    cur_col, cur_row = 0, 0
    for i in range(length+1):
        if i != 0:
            cur_row += 1
        for row in range(cur_row, n):
            if graph[row][cur_col] == 0:
                graph[row][cur_col] = num
                cur_row = row
                num -= 1
            else:
                break

        for col in range(cur_col+1, n):
            if graph[cur_row][col] == 0:
                graph[cur_row][col] = num
                cur_col = col
                num -= 1
            else:
                break

        for row in range(cur_row -1, -1, -1):
            if graph[row][cur_col] == 0:
                graph[row][cur_col] = num
                cur_row = row
                num -= 1
            else:
                break

        for col in range(cur_col - 1, -1, -1):
            if graph[cur_row][col] == 0:
                graph[cur_row][col] = num
                cur_col = col
                num -= 1
            else:
                break

    for g in graph:
        print(' '.join(map(str, g)))

    for row in range(n):
        for col in range(n):
            if graph[row][col] == m:
                print(row+1, col+1)
                break
profile
알고리즘 정리 블로그입니다.

0개의 댓글