劍指offer(19)順時針打印矩陣
阿新 • • 發佈:2018-09-07
行數 div function sub amp pri ott 16px 依次
題目描述:
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 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.解題代碼:
function printMatrix(matrix)
{
// write code here
//定義四個參數來定位打印的範圍
var bottom = matrix.length - 1,top = 0;
var right = matrix[0].length - 1,left = 0;
var result = [];
//控制條件為 >= 是因為有可能只有一行(top == bottom)或者只有一列(left == right)
//當從左往右打印了一行之後,只有當top != bottom時才可以從右往左打印
//當從上往下打印了一行之後,只有當left != right時才可以從下往上打印
while(left <= right && top <= bottom){
//從左往右打印一行
for(var i = left;i <= right;i++){
result.push(matrix[top][i]);
}
//從上往下打印一行(此時top的定位需要加1)
for(var i = top + 1;i <= bottom;i++){
result.push(matrix[i][right]);
}
//從右往左打印一行(此時right的定位需要減1)
if(bottom != top){
for(var i = right - 1;i >= left;i--){
result.push(matrix[bottom][i]);
}
}
//從下往上打印一行(此時bottom的定位需要加1)
//從右往左打印時,從一行的第一個數開始打印,所以此時打印的行數不能 = top
if(left != right){
for(var i = bottom - 1;i > top;i--){
result.push(matrix[i][left]);
}
}
top++, left++, right--, bottom--;
}
return result;
}
劍指offer(19)順時針打印矩陣