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