54.M 螺旋矩阵

Problem: 54. 螺旋矩阵

思路

模拟旋转过程,通过directions定义四个方向,然后依次向右、下、左、上循环。

同时用一个矩阵visited保存已经访问过的元素,如果下一个坐标是已经访问过的,或者已经超出矩阵边界,则旋转方向。

停止条件为返回结果的长度等于矩阵中元素的数量。

需要注意的点:

  • 超出边界的处理

  • 注意调整方向时不能只是+1,还需要取模

Code

var directions = [][]int{
	{0, 1},
	{1, 0},
	{0, -1},
	{-1, 0},
}

func spiralOrder(matrix [][]int) []int {
	visited := make([][]int, len(matrix))
	for i := 0; i < len(matrix); i++ {
		visited[i] = make([]int, len(matrix[0]))
	}

	var ans []int
	i, j := 0, 0
	direction := 0
	for len(ans) < len(matrix)*len(matrix[0]) {
		if visited[i][j] == 0 {
			ans = append(ans, matrix[i][j])
			visited[i][j] = 1
		}

		nextI := i + directions[direction][0]
		nextJ := j + directions[direction][1]
		if nextI < 0 || nextI >= len(matrix) || nextJ < 0 || nextJ >= len(matrix[0]) || visited[nextI][nextJ] == 1 {
			direction = (direction + 1) % len(directions)
		}

		i += directions[direction][0]
		j += directions[direction][1]
	}

	return ans
}

Last updated

Was this helpful?