Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
990 B
2
Indexable
def fill_spiral_matrix(N):
    matrix = [[0] * N for _ in range(N)]  # Create an NxN matrix filled with zeros

    x, y = 0, 0  # Initial coordinates
    num = N * N  # Start from N*N and decrement

    # Directions: right, down, left, up
    dx = [0, 1, 0, -1]
    dy = [1, 0, -1, 0]
    direction = 0  # Initial direction: right

    for _ in range(N * N):
        matrix[x][y] = num  # Fill the current cell with the current number
        num -= 1

        nx = x + dx[direction]
        ny = y + dy[direction]

        # Change direction if the next cell is out of bounds or already filled
        if nx < 0 or nx >= N or ny < 0 or ny >= N or matrix[nx][ny] != 0:
            direction = (direction + 1) % 4
            nx = x + dx[direction]
            ny = y + dy[direction]

        x, y = nx, ny

    return matrix

# Example usage:
N = int(input("Enter an odd number N: "))
matrix = fill_spiral_matrix(N)

# Print the matrix
for row in matrix:
    print(' '.join(map(str, row)))