/**
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
class Maplx {
constructor(args) {
this.data = args
this.top = 0
this.bottom = args.length - 1
this.left = 0
if(args[0]){
this.right = args[0].length - 1
}
Object.freeze(this)
}
getArr(point) {
if (this.bottom < 0 || this.right < 0) {
return []
}
if (this.bottom === 0) {
return this.data[0]
}
let res = []
const r = {
type: 'right',
after: 'top',
axis: 'x'
},
b = {
type: 'bottom',
after: 'right',
axis: 'y'
},
l = {
type: 'left',
after: 'bottom',
axis: 'x'
},
t = {
type: 'top',
after: 'left',
axis: 'y'
}
const loop = [r, b, l, t]
const wall = {
top: point.y,
bottom: this.bottom,
left: this.left,
right: this.right
}
while (!(wall.bottom < wall.top || wall.right < wall.left)) {
loop.map((item, i) => {
if (wall.bottom < wall.top || wall.right < wall.left) {
return
}
const a = this.go(point, item.type, wall[item.type])
point[item.axis] = wall[item.type]
if (i === 1 || i === 2) {
wall[item.after]--
} else {
wall[item.after]++
}
res = res.concat(a)
})
}
res.push(this.data[point.y][point.x])
return res
}
go({
x,
y
}, type, wall) {
const res = []
switch (type) {
case 'bottom': //向下遍历
if (wall > this.bottom) wall = this.bottom
for (let i = y; i < wall; i++) {
res.push(this.data[i][x])
}
break;
case 'top': //向上遍历
if (wall < this.top) wall = this.top
for (let i = y; i > wall; i--) {
res.push(this.data[i][x])
}
break;
case 'right': //向右遍历
if (wall > this.right) wall = this.right
for (let i = x; i < wall; i++) {
res.push(this.data[y][i])
}
break;
case 'left': //向左遍历
if (wall < this.left) wall = this.left
for (let i = x; i > wall; i--) {
res.push(this.data[y][i])
}
break;
default:
break
}
return res
}
}
function spiralOrder( matrix ) {
// write code here
const maplx = new Maplx(matrix)
const point = {
x:0,
y:0
}
return maplx.getArr(point)
}
module.exports = {
spiralOrder : spiralOrder
};
小题大做一下