题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
/**
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
function spiralOrder( matrix ) {
let result = [];
if (matrix.length == 0) return result;
let m = matrix.length, n = matrix[0].length;
const dir = [[0, 1],[1, 0],[0, -1],[ -1, 0]];
let x = 0,y=0;
let d = 0;
for (let i = 0; i< m*n; i++) {
result.push(matrix[x][y]);
matrix[x][y] = Number.MAX_SAFE_INTEGER;
let dx = x + dir[d][0], dy = y + dir[d][1];
if (dx < 0 || dx >= m || dy < 0 || dy >= n || matrix[dx][dy] == Number.MAX_SAFE_INTEGER) {
d = (d + 1) % 4;
dx = x + dir[d][0];
dy = y + dir[d][1];
}
x = dx;
y = dy;
}
return result;
}
module.exports = {
spiralOrder : spiralOrder
};