목차

숫자채우기

ps
링크acmicpc.net/…
출처BOJ
문제 번호2041
문제명숫자채우기
레벨다이아몬드 5
분류

애드혹

시간복잡도O(nm)
인풋사이즈n<=1000, m<=1000
사용한 언어Python
제출기록30860KB / 556ms
최고기록556ms
해결날짜2022/03/04

풀이

코드

코드 - 1 (대각 방향)

"""Solution code for "BOJ 2041. 숫자채우기".

- Problem link: https://www.acmicpc.net/problem/2041
- Solution link: http://www.teferi.net/ps/problems/boj/2041

Tags: [Ad Hoc]
"""


def main():
    N, M = [int(x) for x in input().split()]
    answer = [[None] * M for _ in range(N)]

    sign = 1
    p = 0
    answer[0][0] = N * M
    for i in range(1, N + M - 1):
        sign *= -1
        first, last = max(0, i - M + 1), min(N - 1, i) + 1
        for j in range(first, last):
            p += 2 if j > 0 and i - j > 0 else 1
            if i - j == 0:
                answer[j][i - j] = answer[i - 1][i - j] + p * sign
            else:
                answer[j][i - j] = answer[j][i - j - 1] + p * sign
    for row in answer:
        print(*row)


if __name__ == '__main__':
    main()

코드 - 2 (가로 방향)

"""Solution code for "BOJ 2041. 숫자채우기".

- Problem link: https://www.acmicpc.net/problem/2041
- Solution link: http://www.teferi.net/ps/problems/boj/2041

Tags: [Ad Hoc]
"""

import itertools


def main():
    N, M = [int(x) for x in input().split()]

    left_num = N * M
    for diff, sign in zip(range(1, 1 + N * (M * 2 - 1), M * 2 - 1),
                          itertools.cycle([1, -1])):
        sign_iter = itertools.cycle([sign, -sign])
        v = left_num
        row = [v] + [(v := v + x * s)
                     for x, s in zip(range(diff, diff + M - 1), sign_iter)]
        print(*row)
        left_num += (diff + M - 1) * sign


if __name__ == '__main__':
    main()