题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
function printMatrix(matrix) { // write code here if (matrix.length === 0 || matrix[0].length === 0) return []; let left = 0; let right = matrix[0].length - 1; let bottom = 0; let top = matrix.length - 1; const res = []; while (left <= right && top >= bottom) { for (let i = left; i <= right; i++) { res.push(matrix[bottom][i]); } bottom++; if (bottom > top) break; for (let i = bottom; i <= top; i++) { res.push(matrix[i][right]); } right--; if (left > right) break; for (let i = right; i >= left; i--) { res.push(matrix[top][i]); } top--; if (bottom > top) break; for (let i = top; i >= bottom; i--) { res.push(matrix[i][left]); } left++; if (left > right) break; } return res; } module.exports = { printMatrix: printMatrix, };