leetcode-54-Spiral-Matrix

描述


Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

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

分析


模拟题,注意边界情况即可。

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
while matrix and matrix[0]:
if matrix and matrix[0]:
result += matrix.pop(0)
if matrix and matrix[0]:
for row in matrix:
result.append(row.pop())
if matrix and matrix[0]:
result += matrix.pop()[::-1]
if matrix and matrix[0]:
for row in matrix[::-1]:
result.append(row.pop(0))
return result

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 || len(matrix[0]) == 0 {
return []int{}
}

rows, columns := len(matrix), len(matrix[0])
visited := make([][]bool, rows)
for i := 0; i < rows; i++ {
visited[i] = make([]bool, columns)
}

var (
total = rows * columns
result = make([]int, total)
row, column = 0, 0
directions = [][]int{[]int{0, 1}, []int{1, 0}, []int{0, -1}, []int{-1, 0}}
directionIndex = 0
)

for i := 0; i < total; i++ {
result[i] = matrix[row][column]
visited[row][column] = true
nextRow, nextColumn := row + directions[directionIndex][0], column + directions[directionIndex][1]
if nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn] {
directionIndex = (directionIndex+1) % 4
}
row += directions[directionIndex][0]
column += directions[directionIndex][1]
}
return result
}

相关问题


题目来源