一、题意
给定一个包含 n x m 个元素的矩阵(n 行,m 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
例如,如果输入如下矩阵:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
二、参考Leetcode原题
LeetCode 54. Spiral Matrix
三、代码实现
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
import "fmt"
func PrintMatrix(matrix [][]int) []int { var res []int n := len(matrix) if n == 0 { return res } m := len(matrix[0]) nm := n * m layer := 0 startN, endN, startM, endM := 0, 0, 0, 0 for nm > 0 { startN, endN = layer, n-layer-1 startM, endM = layer, m-layer-1
for i := startM; i <= endM && nm > 0; i++ { res = append(res, matrix[startN][i]) nm-- }
for i := startN+1; i <= endN && nm > 0; i++ { res = append(res, matrix[i][endM]) nm-- }
for i := endM-1; i >= startM && nm > 0; i-- { res = append(res, matrix[endN][i]) nm-- }
for i := endN-1; i >= startN+1 && nm > 0; i-- { res = append(res, matrix[i][startM]) nm-- }
layer++ } return res }
func main() { var matrix [][]int = [][]int {{1, 2}, {4, 5}, {7, 8}} res := PrintMatrix(matrix) fmt.Print(res) }
[1 2 5 8 7 4] Process finished with exit code 0
|