返回

如何理解螺旋矩阵中的奥秘

后端

一、螺旋矩阵
螺旋矩阵的题目要求如下:

给定一个二维数组matrix,其中包含m x n个整数,请你将该数组中的元素按螺旋顺序输出。

例如,对于以下二维数组:

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

输出应为:

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

实现方法:

  1. 定义四个指针top, bottom, left, right ,分别指向矩阵的顶部、底部、左边界和右边界。
  2. 定义一个空的列表result来存储输出结果
  3. 使用while循环,只要top <= bottom和left <= right,就一直循环
  4. 在循环中,将矩阵中从left到right列、从top到bottom行上的元素按顺序添加到result中
  5. 然后,将top加1,将bottom减1,将left加1,将right减1 ,缩小矩阵的范围。
  6. 重复步骤3和4,直到top > bottom或left > right

代码实现:

def spiral_matrix(matrix):
    if not matrix:
        return []

    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1
    result = []

    while top <= bottom and left <= right:
        for i in range(left, right + 1):
            result.append(matrix[top][i])
        for i in range(top + 1, bottom):
            result.append(matrix[i][right])
        if top < bottom:
            for i in range(right, left - 1, -1):
                result.append(matrix[bottom][i])
        if left < right:
            for i in range(bottom - 1, top, -1):
                result.append(matrix[i][left])
        top += 1
        bottom -= 1
        left += 1
        right -= 1

    return result

二、螺旋矩阵II

螺旋矩阵II的题目要求如下:

给定一个正整数n,生成一个n x n的螺旋矩阵,矩阵中的元素按螺旋顺序递增排列。

例如,对于n = 3,输出应为:

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

实现方法:

  1. 创建一个n x n的二维数组matrix,并将其所有元素初始化为0
  2. 定义变量row和col,分别指向当前行和当前列
  3. 定义变量count,表示当前要填充的元素值
  4. 使用while循环,只要count小于等于n 2,就一直循环。
  5. 在循环中,将matrix[row][col]设置为count,并将count加1
  6. 然后,根据当前的位置,更新row和col的值
  7. 重复步骤3和4,直到count大于n 2。

代码实现:

def spiral_matrix_ii(n):
    matrix = [[0] * n for _ in range(n)]
    row, col = 0, 0
    count = 1

    while count <= n ** 2:
        matrix[row][col] = count
        count += 1

        if row == 0 or matrix[row - 1][col] != 0:
            col += 1
        else:
            row -= 1

        if col == n - 1 or matrix[row][col + 1] != 0:
            row += 1
        else:
            col -= 1

        if row == n - 1 or matrix[row + 1][col] != 0:
            col -= 1
        else:
            row += 1

        if col == 0 or matrix[row][col - 1] != 0:
            row -= 1
        else:
            col += 1

    return matrix