在地铁上想出来的一道题 , 模拟出了四面"墙"的模型
伪代码:
pesudo code:
For right down left up direction
Check resCount at every movement
Move m- left - right step
Move n- down - up step
Maintain 4 wall variable
Return res
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}
res := []int{}
resCount := 0
n := len(matrix)
m := len(matrix[0])
//初始化四面墙都为 0 的厚度
uw:=0
rw:=0
dw:=0
lw:=0
//当前位置坐标初始化
curPosH:=0
curPosV:=-1
for {
//由于有墙的存在 , 只能移动 m-rw-lw , 下面的同理
for i := 1; i <= m-rw-lw; i++ {
curPosV++
meta := matrix[curPosH][curPosV]
res = append(res, meta)
resCount++
}
//维护墙的厚度变量
uw+=1
//检查是否已经走完
if resCount == m*n {
break
}
for i := 1; i <= n-uw-dw; i++ {
curPosH++
meta := matrix[curPosH][curPosV]
res = append(res, meta)
resCount++
}
rw+=1
if resCount == m*n {
break
}
for i := 1; i <= m-rw-lw; i++ {
curPosV--
meta := matrix[curPosH][curPosV]
res = append(res, meta)
resCount++
}
dw+=1
if resCount == m*n {
break
}
for i := 1; i <= n-dw-uw; i++ {
curPosH--
meta := matrix[curPosH][curPosV]
res = append(res, meta)
resCount++
}
lw+=1
if resCount == m*n {
break
}
}
return res
}