在地鐵上想出來(lái)的一道題 , 模擬出了四面"墻"的模型
image.png
偽代碼:
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
//當(dāng)前位置坐標(biāo)初始化
curPosH:=0
curPosV:=-1
for {
//由于有墻的存在 , 只能移動(dòng) m-rw-lw , 下面的同理
for i := 1; i <= m-rw-lw; i++ {
curPosV++
meta := matrix[curPosH][curPosV]
res = append(res, meta)
resCount++
}
//維護(hù)墻的厚度變量
uw+=1
//檢查是否已經(jīng)走完
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
}