題目:給出一個m * n的矩陣(m行,n列),請按照順時針螺旋順序返回元素。例如,給出以下矩陣:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
複製程式碼
應該返回[1,2,3,6,9,8,7,4,5]
.
我的解答:
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
var rawPointer = 0; //行指標
var colPointer = 0; //列指標
if (!matrix) {
matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
}
var raw = matrix.length;
if (raw < 2 && !matrix[0]) {
return matrix;
}
var col = matrix[0].length;
var _raw = raw,
_col = col;
var tempArr = [];
var isReadingLine = true;
var rawFlag = -1;
var colFlag = -1;
for (var i = 0; i < raw * col;) {
if (isReadingLine) {
//讀行
colFlag = -colFlag;
for(var m = 0; m < _col; m ++,colPointer += colFlag) {
tempArr.push(matrix[rawPointer][colPointer]);
}
//恢復行指標到行指標方向末尾
colPointer -= colFlag;
isReadingLine = false;
//總執行進度跳躍
i += _col;
//執行完一行之後,下次列迴圈長度減1
_raw --;
//列指標向前挺進加1
rawPointer += colFlag;
} else {
//讀列
rawFlag = -rawFlag;
for(var n = 0; n < _raw; n ++, rawPointer += rawFlag) {
tempArr.push(matrix[rawPointer][colPointer]);
}
//恢復行指標到行指標方向末尾
rawPointer -= rawFlag;
isReadingLine = true;
//執行完一行之後,下次行迴圈長度減1
i += _raw;
_col --;
//行指標往後退一位
colPointer -= rawFlag;
}
}
return tempArr;
}
複製程式碼