LeetCode刷题日记之顺时针打印矩阵

158 阅读1分钟

个人博客网站欢迎交流:萤火之森:https://blog.xkongkeji.com

解题思路:把矩阵分为一个一个的圆环,顺时针遍历圆环即可(设置边界值,根据边界值,遍历圆环),只剩下一行,从左到右依次添加,只剩下一列时,从上到下依次添加。

let matrix = [    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
let spiralOrder = (matrix) => {
    if (matrix.length == 0) return [];
    let result = [];
    let top = 0;
    let bottom = matrix.length - 1;
    let left = 0;
    let right = matrix[0].length - 1;
    while (top < bottom && left < right) {
        for (let i = left; i < right; i++) result.push(matrix[top][i]);
        for (let i = top; i < bottom; i++) result.push(matrix[i][right]);
        for (let i = right; i > left; i--) result.push(matrix[bottom][i]);
        for (let i = bottom; i > top; i--) result.push(matrix[i][left]);
        right--;
        top++;
        bottom--;
        left++;
    }
    // 剩下一行,从左到右依次添加
    if (top == bottom) {
        for (let i = left; i <= right; i++) {
            result.push(matrix[top][i]);
        }
    }else if (left == right) {
        for (let i = top; i <= bottom; i++) {
            result.push(matrix[i][left]);
        }
    }
    return result;
};
console.log(spiralOrder(matrix));