当前位置: 首页 > 工具软件 > go-matrix > 使用案例 >

[leetcode-in-go] 0054-Spiral Matrix

景鹏云
2023-12-01

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

解题思路

  • 直接模拟的绕圈(这个题的意义难道是考下标越界么,折腾好久终于不越界了 -_-|||)
func spiralOrder(matrix [][]int) []int {

	if len(matrix) == 0 {
		return []int{}
	}

	m := len(matrix)
	n := len(matrix[0])
	length := m * n
	result := make([]int, length)
	row, col, round, cnt := 0, 0, 0, 0

L:
	for {
		for ; col < n-round; col++ {
			result[cnt] = matrix[row][col]
			cnt++
			if cnt == length {
				break L
			}
		}
		col--
		for row = row + 1; row < m-round; row++ {
			result[cnt] = matrix[row][col]
			cnt++
			if cnt == length {
				break L
			}
		}
		row--
		for col = col - 1; col >= 0+round; col-- {
			result[cnt] = matrix[row][col]
			cnt++
			if cnt == length {
				break L
			}
		}
		col++
		for row = row - 1; row >= 1+round; row-- {
			result[cnt] = matrix[row][col]
			cnt++
			if cnt == length {
				break L
			}
		}
		row++
		col++
		round++
	}
	return result
}

 类似资料: