summaryrefslogtreecommitdiff
path: root/day2.5/task1/task1.py
blob: f7ce69022779ebd2eca230cc0ae6352c788aca41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
n = int(input())
RIGHT, DOWN, LEFT, UP = range(4)

matrix = [[0 for _ in range(n)] for _ in range(n)]

current = [0, 0]
direction = RIGHT

for i in range(1, n ** 2 + 1):
    matrix[current[1]][current[0]] = i

    if direction == RIGHT:
        if current[0] + 1 >= n or matrix[current[1]][current[0] + 1] != 0:
            direction = DOWN
            current[1] += 1
        else:
            current[0] += 1

    elif direction == DOWN:
        if current[1] + 1 >= n or matrix[current[1] + 1][current[0]] != 0:
            direction = LEFT
            current[0] -= 1
        else:
            current[1] += 1

    elif direction == LEFT:
        if current[0] - 1 < 0 or matrix[current[1]][current[0] - 1] != 0:
            direction = UP
            current[1] -= 1
        else:
            current[0] -= 1

    elif direction == UP:
        if current[1] - 1 < 0 or matrix[current[1] - 1][current[0]] != 0:
            direction = RIGHT
            current[0] += 1
        else:
            current[1] -= 1


# Переводим все числа в строки и делаем их необходимой длины, чтобы вывод был наглядным
# Длина, до которой дополняем все числа, точно будет равна длине самого большого числа в матрице
maxlen = len(str(n ** 2))
for row in matrix:
    print(*map(lambda num: str(num).rjust(maxlen, ' '), row))