結果

問題 No.401 数字の渦巻き
ユーザー lam6er
提出日時 2025-03-20 18:54:43
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 42 ms / 2,000 ms
コード長 925 bytes
コンパイル時間 367 ms
コンパイル使用メモリ 82,504 KB
実行使用メモリ 54,340 KB
最終ジャッジ日時 2025-03-20 18:56:23
合計ジャッジ時間 2,415 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

n = int(input())
if n == 0:
    exit()

grid = [[0 for _ in range(n)] for _ in range(n)]
current_row, current_col = 0, 0
grid[current_row][current_col] = 1
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # right, down, left, up
current_dir = 0  # start with right

for num in range(2, n * n + 1):
    dr, dc = directions[current_dir]
    next_row = current_row + dr
    next_col = current_col + dc

    # Check if the next cell is valid (within bounds and not filled)
    if 0 <= next_row < n and 0 <= next_col < n and grid[next_row][next_col] == 0:
        current_row, current_col = next_row, next_col
    else:
        # Change direction clockwise
        current_dir = (current_dir + 1) % 4
        dr, dc = directions[current_dir]
        current_row += dr
        current_col += dc

    grid[current_row][current_col] = num

for row in grid:
    formatted = [f"{num:03d}" for num in row]
    print(" ".join(formatted))
0