【JavaScript】顺时针打印矩阵的问题

顺时针打印矩阵のJavaScript实现

这道题是牛客网上剑指offer的一道题目原题链接

1. 递归

这个实现思路,重点在于分析log函数内部圈数n与矩阵坐标之间的关系,比较复杂
只能打印n*n的方阵

function printMatrix(matrix) {
    // write code here
    var result = [];
    // 递归
    var order = matrix.length;

    function log(n) {
        // top
        for (let i = 0; i < n; i++) {
            result.push(matrix[(order - n) / 2][((order - n) / 2 + i)]);
        }
        if (n > 1) {
            // right
            for (let i = 1; i < n - 1; i++) {
                result.push(matrix[(order - n) / 2 + i][(order - n) / 2 + n - 1]);
            }
            // bottom
            for (let i = 0; i < n; i++) {
                result.push(matrix[order - 1 - (order - n) / 2][(order - n) / 2 + n - 1 - i]);
            }
            // left
            for (let i = 1; i < n - 1; i++) {
                result.push(matrix[order - 1 - (order - n) / 2 - i][(order - n) / 2]);
            }
        }
    }
    var cur = order;
    while (cur > 0) {
        log(cur);
        cur = cur - 2;
    }
    return result;
}

2. 指针标记

对左上角和右下角位置进行记录,一圈一圈的“剥皮”
每一个独立的圈只有三种可能:单行的只打印上;单列的打印上和右;完整圈打印上右下左

function printMatrix(matrix) {
    // write code here
    var result = [];
    var rows = matrix.length;
    var cols = matrix[0].length;
    /* 要四个指针 */
    var topLeft_x = 0,
        topLeft_y = 0;
    var rightBottom_x = rows - 1,
        rightBottom_y = cols - 1

    while (topLeft_x <= rightBottom_x && topLeft_y <= rightBottom_y) {
        // top
        for (let i = topLeft_y; i <= rightBottom_y; i++) {
            result.push(matrix[topLeft_x][i]);
        }
        if (topLeft_x === rightBottom_x) {
            break;
        }
        // right
        for (let i = topLeft_x + 1; i <= rightBottom_x; i++) {
            result.push(matrix[i][rightBottom_y]);
        }
        if (topLeft_y === rightBottom_y) {
            break;
        }
        // bottom
        for (let i = rightBottom_y - 1; i >= topLeft_y; i--) {
            result.push(matrix[rightBottom_x][i]);
        }
        // left
        for (let i = rightBottom_x - 1; i >= topLeft_x + 1; i--) {
            result.push(matrix[i][topLeft_y]);
        }
        topLeft_y++;
        topLeft_x++;
        rightBottom_y--;
        rightBottom_x--;
    }
    return result;
}

版权声明:本文为pangji0417原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。