蛇形填充 n 阶方阵问题 | 豆包MarsCode AI 刷题

62 阅读3分钟

蛇形填充 n 阶方阵问题解析

问题描述

小U面临一个有趣的任务:在一个 ( n \times n ) 的方阵中填入 1 到 ( n \times n ) 这些数字,并要求按照蛇形顺序从右上角开始,沿着方阵的边界顺时针进行填充。蛇形填充的特殊排列方式使得每一层数字呈现出波浪形的排列方式。例如,当 ( n = 4 ) 时,方阵应如下所示:

10 11 12 1
9 16 13 2
8 15 14 3
7  6  5  4

你需要编写程序输出填充后的方阵,确保格式的整齐性。

核心问题

核心问题是按照蛇形顺序从右上角开始,沿着方阵的边界顺时针填充数字。每个数字必须依次填入,并且在遇到边界或已填充的位置时改变方向。

解题思路

  1. 初始化矩阵:创建一个 ( n * n ) 的矩阵,初始值全部为0。
  2. 定义方向:定义四个方向:右、下、左、上。
  3. 初始位置和方向:从右上角开始,初始方向为向左。
  4. 填充数字:从1到 ( n * n ) 依次填充数字。
  5. 改变方向:在每次填充后,计算下一个位置。如果下一个位置越界或已经填充过,则改变方向。
  6. 更新位置:更新当前的位置为下一个位置。

主要逻辑

  1. 初始化矩阵

    matrix = [[0] * n for _ in range(n)]
    
  2. 定义方向

    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # 右、下、左、上
    
  3. 初始位置和方向

    x, y = 0, n - 1  # 从右上角开始
    direction_index = 3  # 初始方向为左
    
  4. 填充数字

    for num in range(1, n * n + 1):
        # 填充当前位置
        matrix[x][y] = num
        
        # 计算下一个位置
        next_x = x + directions[direction_index][0]
        next_y = y + directions[direction_index][1]
        
        # 检查下一个位置是否越界或已经填充过
        if not (0 <= next_x < n and 0 <= next_y < n and matrix[next_x][next_y] == 0):
            # 改变方向
            direction_index = (direction_index + 1) % 4
            next_x = x + directions[direction_index][0]
            next_y = y + directions[direction_index][1]
        
        # 更新当前位置
        x, y = next_x, next_y
    
  5. 返回结果

    return matrix
    

代码实现

def solution(n: int) -> list:
    # 初始化一个 n x n 的矩阵,所有元素为 0
    matrix = [[0] * n for _ in range(n)]
    
    # 定义四个方向:右、下、左、上
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    
    # 初始位置和方向
    x, y = 0, n - 1  # 从右上角开始
    direction_index = 3  # 初始方向为左
    
    # 填充数字
    for num in range(1, n * n + 1):
        # 填充当前位置
        matrix[x][y] = num
        
        # 计算下一个位置
        next_x = x + directions[direction_index][0]
        next_y = y + directions[direction_index][1]
        
        # 检查下一个位置是否越界或已经填充过
        if not (0 <= next_x < n and 0 <= next_y < n and matrix[next_x][next_y] == 0):
            # 改变方向
            direction_index = (direction_index + 1) % 4
            next_x = x + directions[direction_index][0]
            next_y = y + directions[direction_index][1]
        
        # 更新当前位置
        x, y = next_x, next_y
    
    return matrix

if __name__ == '__main__':
    print(solution(4) == [[10, 11, 12, 1], [9, 16, 13, 2], [8, 15, 14, 3], [7, 6, 5, 4]])
    print(solution(5) == [[13, 14, 15, 16, 1], [12, 23, 24, 17, 2], [11, 22, 25, 18, 3], [10, 21, 20, 19, 4], [9, 8, 7, 6, 5]])
    print(solution(3) == [[7, 8, 1], [6, 9, 2], [5, 4, 3]])

复杂度分析

  • 时间复杂度

    • 初始化矩阵的时间复杂度为 (O(n^2))。
    • 填充数字的时间复杂度为 (O(n^2)),因为需要遍历 (n^2) 个位置。
    • 总的时间复杂度为 (O(n^2))。
  • 空间复杂度

    • 初始化矩阵需要 (O(n^2)) 的额外空间。
    • 其他变量占用的空间是常数级别的,所以总体空间复杂度为 (O(n^2))。