牛客网: BM98
题目: 螺旋式返回矩阵所有元素
思路: 初始化边界指针left = 0, right = n-1, up = 0, down = n-1, 遍历条件为up<=down&&left<=right,每次遍历完一行、列时改变up/down/left/right后需要对停止条件进行判断提前结束外层循环。
代码:文章来源:https://uudwc.com/A/Lap4E
// go
package main
// import "fmt"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
func spiralOrder( matrix [][]int ) []int {
// write code here
if len(matrix) == 0 || len(matrix[0]) == 0 {
return []int{}
}
up := 0
down := len(matrix) - 1
left := 0
right := len(matrix[0]) - 1
res := []int{}
for up <= down && left <= right {
for i := left; i <= right; i++ {
res = append(res, matrix[up][i])
}
up++
if up > down {
break
}
for i := up; i <= down; i++ {
res = append(res, matrix[i][right])
}
right--
if left > right {
break
}
for i := right; i >= left; i-- {
res = append(res, matrix[down][i])
}
down--
if up > down {
break
}
for i := down; i >= up; i-- {
res = append(res, matrix[i][left])
}
left++
if left > right {
break
}
}
return res
}
文章来源地址https://uudwc.com/A/Lap4E