题解 | #顺时针打印矩阵#

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

function print(left, right, top, bottom, matrix, res) {
    if (left > right || top > bottom) return;

    for (let i = left; i <= right; i++) res.push(matrix[top][i]);
    top++;

    for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
    right--;

    if (top <= bottom) {
        for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);
        bottom--;
    }

    if (left <= right) {
        for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
        left++;
    }

    print(left, right, top, bottom, matrix, res);
}

function printMatrix(matrix) {
    const res = [];
    if (matrix.length === 0 || matrix[0].length === 0) return res;
    const rows = matrix.length;
    const cols = matrix[0].length;
    print(0, cols - 1, 0, rows - 1, matrix, res);
    return res;
}

module.exports = {
    printMatrix: printMatrix
};

全部评论

相关推荐

贪食滴🐶:你说熟悉扣篮的底层原理,有过隔扣职业球员的实战经验吗
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务