# ac solution code

• ``````    /*
Solution1. time = O(nm); space = O(1)
My Swift: https://discuss.leetcode.com/topic/106402/ac-solution-code
SpiralOrder traverse sequence:
1) Rightward →
2) Downward  ↓
3) Leftward  ←
4) Upward    ↑
*/
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
guard matrix.count > 0 else {return []}
var rowLow = 0, rowHigh = matrix.count - 1, colLow = 0, colHigh = matrix[0].count - 1
var res = [Int]()

while rowLow <= rowHigh && colLow <= colHigh {//Exit case
// 1. Rightward
for j in colLow..<colHigh + 1 {
res.append(matrix[rowLow][j])
}
rowLow += 1

// 2. Downward
for i in rowLow..<rowHigh + 1 {
res.append(matrix[i][colHigh])
}
colHigh -= 1

// 3. Leftward //<-&& rowLow <= rowHigh
for j in stride(from: colHigh, through: colLow, by: -1) where rowLow <= rowHigh {
res.append(matrix[rowHigh][j])
}
rowHigh -= 1

// 4. Upward //<-&& colLow <= rowHigh
for i in stride(from: rowHigh, through: rowLow, by: -1) where colLow <= colHigh {
res.append(matrix[i][colLow])
}
colLow += 1
}
return res
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.