当前位置: 面试刷题>> 螺旋矩阵(经典算法150题)


题目描述

螺旋矩阵(Spiral Matrix) 是一道经典的算法题,要求按照螺旋的顺序填充矩阵。具体来说,给定一个正整数 n,生成一个 n x n 的矩阵,并填充数字从 1 到 n*n,按照顺时针螺旋的顺序进行。

例如,当 n = 3 时,生成的螺旋矩阵如下:

1 2 3
8 9 4
7 6 5

解题思路

  1. 初始化一个 n x n 的矩阵,并设置四个边界:leftrighttopbottom
  2. 按照顺时针方向遍历矩阵:
    • 从左到右填充上边界。
    • 从上到下填充右边界。
    • 从右到左填充下边界。
    • 从下到上填充左边界。
  3. 每完成一个方向的填充后,更新相应的边界。
  4. 重复步骤 2 和 3,直到矩阵被完全填充。

示例代码

PHP 示例

function generateMatrix($n) {
    $matrix = array_fill(0, $n, array_fill(0, $n, 0));
    $left = 0, $right = $n - 1, $top = 0, $bottom = $n - 1;
    $num = 1;

    while ($left <= $right && $top <= $bottom) {
        // 填充上边
        for ($i = $left; $i <= $right; $i++) {
            $matrix[$top][$i] = $num++;
        }
        $top++;

        // 填充右边
        for ($i = $top; $i <= $bottom; $i++) {
            $matrix[$i][$right] = $num++;
        }
        $right--;

        if ($top <= $bottom) {
            // 填充下边
            for ($i = $right; $i >= $left; $i--) {
                $matrix[$bottom][$i] = $num++;
            }
            $bottom--;
        }

        if ($left <= $right) {
            // 填充左边
            for ($i = $bottom; $i >= $top; $i--) {
                $matrix[$i][$left] = $num++;
            }
            $left++;
        }
    }

    return $matrix;
}

// 示例使用
$n = 3;
$result = generateMatrix($n);
foreach ($result as $row) {
    echo implode(' ', $row) . "\n";
}

Python 示例

def generateMatrix(n):
    matrix = [[0] * n for _ in range(n)]
    left, right, top, bottom = 0, n - 1, 0, n - 1
    num = 1

    while left <= right and top <= bottom:
        # 填充上边
        for i in range(left, right + 1):
            matrix[top][i] = num
            num += 1
        top += 1

        # 填充右边
        for i in range(top, bottom + 1):
            matrix[i][right] = num
            num += 1
        right -= 1

        if top <= bottom:
            # 填充下边
            for i in range(right, left - 1, -1):
                matrix[bottom][i] = num
                num += 1
            bottom -= 1

        if left <= right:
            # 填充左边
            for i in range(bottom, top - 1, -1):
                matrix[i][left] = num
                num += 1
            left += 1

    return matrix

# 示例使用
n = 3
result = generateMatrix(n)
for row in result:
    print(' '.join(map(str, row)))

JavaScript 示例

function generateMatrix(n) {
    const matrix = Array.from({ length: n }, () => Array(n).fill(0));
    let left = 0, right = n - 1, top = 0, bottom = n - 1;
    let num = 1;

    while (left <= right && top <= bottom) {
        // 填充上边
        for (let i = left; i <= right; i++) {
            matrix[top][i] = num++;
        }
        top++;

        // 填充右边
        for (let i = top; i <= bottom; i++) {
            matrix[i][right] = num++;
        }
        right--;

        if (top <= bottom) {
            // 填充下边
            for (let i = right; i >= left; i--) {
                matrix[bottom][i] = num++;
            }
            bottom--;
        }

        if (left <= right) {
            // 填充左边
            for (let i = bottom; i >= top; i--) {
                matrix[i][left] = num++;
            }
            left++;
        }
    }

    return matrix;
}

// 示例使用
const n = 3;
const result = generateMatrix(n);
for (let row of result) {
    console.log(row.join(' '));
}

以上代码均生成了一个 n x n 的螺旋矩阵,并按要求打印了结果。

推荐面试题