内容中心

2026年比较好的型材抛丸机厂家对比推荐-江苏巨龙铸造机械有限公司

To solve this problem, we need to generate an n x n spiral matrix where numbers are filled in a spiral order starting from 1 and moving right, down, left, up, and repeating until all cells are filled.

Approach

  1. Matrix Initialization: Create an n x n matrix filled with zeros to store the spiral numbers.
  2. Direction Handling: Use a list of direction tuples to represent the movement directions: right (0, 1), down (1, 0), left (0, -1), up (-1, 0).
  3. Spiral Filling:
    • Start at the top-left corner (0, 0) with the number 1.
    • For each number from 1 to n²:
      • Fill the current cell with the number.
      • Calculate the next position based on the current direction.
      • If the next position is valid (within bounds and not yet filled), move to it.
      • If not, change direction (cycle through the direction list) and move to the new valid position.

Solution Code

def spiral_matrix(n):
    matrix = [[0] * n for _ in range(n)]
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # Right, Down, Left, Up
    current_dir = 0
    row, col = 0, 0

    for num in range(1, n * n + 1):
        matrix[row][col] = num
        # Compute next position
        next_row = row + directions[current_dir][0]
        next_col = col + directions[current_dir][1]

        # Check if next position is valid
        if 0 <= next_row < n and 0 <= next_col < n and matrix[next_row][next_col] == 0:
            row, col = next_row, next_col
        else:
            # Change direction
            current_dir = (current_dir + 1) % 4
            # Move to new direction
            row += directions[current_dir][0]
            col += directions[current_dir][1]

    return matrix

# Example usage
n = 3
print(spiral_matrix(n))

Explanation

  • Matrix Initialization: The matrix is initialized with zeros to ensure we can check if a cell is filled later.
  • Direction List: The directions are cycled through to maintain the spiral pattern. Each direction change happens when we hit the edge of the matrix or a filled cell.
  • Filling Process: For each number, we fill the current cell and then check the next position. If the next position is invalid, we change direction and move to the new valid position, ensuring the spiral continues correctly.

This approach efficiently fills the matrix in O(n²) time complexity, which is optimal since each cell is visited exactly once. The space complexity is O(n²) to store the matrix.

The example usage for n=3 will output the spiral matrix:

[[1, 2, 3], [8, 9, 4], [7, 6, 5]]

This solution handles all positive integer values of n and correctly generates the spiral matrix as required.

江苏巨龙铸造机械有限公司

江苏巨龙铸造机械有限公司



(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?