1. 程式人生 > 實用技巧 >【劍指offer】19 順時針列印矩陣

【劍指offer】19 順時針列印矩陣

題目地址:順時針列印矩陣

題目描述

輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字,例如,如果輸入如下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.

題目示例

輸入:
[[1,2],[3,4]]
返回值:
[1,2,4,3]

解法分析

從外向裡一圈一圈地列印,可以理解為邊界不斷向內收縮的過程,步驟可以分解為:

1.列印上邊界,上邊界向內(下)收縮;

2.列印右邊界,右邊界向內(左)收縮;

3.列印下邊界,下邊界向內(上)收縮;

4.列印左邊界,左邊界向內(右)收縮;

5.迴圈上述步驟直到滿足邊界條件。

要注意收縮後判斷上下、左右邊界是否重合,以此作為跳出迴圈的邊界條件。

程式碼

 1 function printMatrix(matrix)
 2 {
 3     // write code here
 4     var arr = [];
 5     var top = 0;
 6     var right = matrix[0].length - 1;
 7     var bottom = matrix.length - 1;
8 var left = 0; 9 if(matrix === null || matrix.length === 0 || matrix[0].length ===0) return arr; 10 while(true){ 11 for(let col = left; col <= right; col++){ 12 arr.push(matrix[top][col]); 13 } 14 top++; 15 if(top > bottom)break; 16 for
(let row = top; row <= bottom; row++){ 17 arr.push(matrix[row][right]); 18 } 19 right--; 20 if(right < left)break; 21 for(let col = right; col >= left; col--){ 22 arr.push(matrix[bottom][col]); 23 } 24 bottom--; 25 if(bottom < top)break; 26 for(let row = bottom; row >= top; row--){ 27 arr.push(matrix[row][left]); 28 } 29 left++; 30 if(left > right)break; 31 } 32 return arr; 33 }

執行結果