题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
则依次打印出数字
1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题
function printMatrix(m) { // 传入的参数为null或者不是数组或者是空数组 if(!m || !Array.isArray(m) || m.length === 0) return []; // 传入的是一维数组 if(!m[0].length) m = [m] var left = 0, right = m[0].length-1, top = 0, down = m.length-1; var res = []; while(left <= right && top <= down) { if(top === down) { for(var i = left;i <= right;i++) res.push(m[top][i]); } else if(left === right) { for(var i = top;i <= down;i++) res.push(m[i][left]); } else { var curCol = left, curRow = top; while(curCol !== right) { res.push(m[top][curCol++]); } while(curRow !== down) { res.push(m[curRow++][right]) } while(curCol !== left) { res.push(m[down][curCol--]); } while(curRow !== top) { res.push(m[curRow--][left]); } } left++; right--; top++; down--; } return res; }