Closed Jogiter closed 5 years ago
{ /** [ [ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16] ] 矩阵顺时针打印结果为:1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 while(x > 2, y > 2) (x, y) y++; (x, y) x++; (x, y) y--; (x, y) x--; */ let matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ] function getRound(matrix, res = []) { let cols = matrix[0].length let rows = matrix.length let _matrix = [].concat(matrix) let _first = matrix[0] let _last = matrix[rows - 1].reverse() let _ends = [] let _starts = [] if (cols > 2 && rows > 2) { _matrix.splice(rows - 1, 1) _matrix.splice(0, 1) for (let y = 0; y < _matrix.length; y++) { _ends.push(_matrix[y][_matrix[y].length - 1]) _starts.push(_matrix[y][0]) _matrix[y].splice(_matrix[y].length - 1, 1) _matrix[y].splice(0, 1) } res = [].concat(_first, _ends, _last, _starts.reverse()) return getRound(_matrix, res) } else { return [].concat(res, _first, _last) } } let output = getRound(matrix, []) console.log(output) // [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10] }
顺时针打印矩阵