题解 | #螺旋矩阵#

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

package main

/**
 *
 * @param matrix int整型二维数组
 * @return int整型一维数组
 */
func spiralOrder(matrix [][]int) []int {
	n := len(matrix)
	res := make([]int, 0)
	if n <= 0 {
		return res
	}
	m := len(matrix[0])
	dx := []int{0, 1, 0, -1}
	dy := []int{1, 0, -1, 0}
	ranX := []int{0, n - 1}
	ranY := []int{0, m - 1}
	dir := 0
	for i, j := 0, 0; ranX[0] <= ranX[1] && ranY[0] <= ranY[1]; {
		res = append(res, matrix[i][j])
		if dir == 0 && j == ranY[1] {
			dir = 1
			//ranY[1]--
			ranX[0]++
		} else if dir == 1 && i == ranX[1] {
			dir = 2
			ranY[1]--
		} else if dir == 2 && j == ranY[0] {
			dir = 3
			ranX[1]--
		} else if dir == 3 && i == ranX[0] {
			dir = 0
			ranY[0]++
		}
		i += dx[dir]
		j += dy[dir]
	}
	return res
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务