首页 > 试题广场 >

螺旋矩阵

[编程题]螺旋矩阵
  • 热度指数:1222 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个包含 m x n 个元素的矩阵(m , n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素
示例1

输入

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

输出

[1,2,3,4,8,12,11,10,9,5,6,7]
function SpiralMatrix( matrix ) {
    // write code here
    // 矩阵为空的情况
    if(matrix.length === 0) return []
    // 定义边界条件,分别是四个方向上下左右
    let top = 0
    let bottom = matrix.length - 1
    let left = 0
    let right = matrix[0].length - 1
    // 旋转方向
    let direction = "right"
    // 定义一个接收答案的数组
    let result = []
    // 开始循环的条件,方向是右下左上
    while(left<=right && top<=bottom){
        // 方向向右时
        if(direction === "right"){
             for(let i=left;i<=right;i++){  // 循环遍历矩阵的top行
                 result.push(matrix[top][i])  // 将矩阵的top行中的每一个元素都push到result数组
             }
            top++
            direction = "down"  // 将方向改为向下
        }
        // 方向向下时
        else if(direction === "down"){
             for(let i=top;i<=bottom;i++){  // 循环遍历矩阵的right列
                 result.push(matrix[i][right])  // 将矩阵的right列中的每一个元素都push到result数组
             }
            right--
            direction = "left"  // 将方向改为向左
        }
        // 方向向左时
        else if(direction === "left"){
             for(let i=right;i>=left;i--){
                 result.push(matrix[bottom][i])
             }
            bottom--
            direction = "top"  // 将方向改为向上
        }
        // 方向向右时
        else if(direction === "top"){
             for(let i=bottom;i>=top;i--){
                 result.push(matrix[i][left])
             }
            left++
            direction = "right"  // 将方向改为向右
        }
    }
    return result
}

发表于 2022-06-15 11:13:11 回复(0)