Skip to content

Commit ca71b40

Browse files
committed
数组: 螺旋矩阵
Change-Id: I6c41f251317712d76ce517d0d9769550825cae42
1 parent 3f8592e commit ca71b40

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

go/leetcode/54.螺旋矩阵.go

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* @lc app=leetcode.cn id=54 lang=golang
3+
*
4+
* [54] 螺旋矩阵
5+
*
6+
* https://leetcode-cn.com/problems/spiral-matrix/description/
7+
*
8+
* algorithms
9+
* Medium (37.01%)
10+
* Likes: 215
11+
* Dislikes: 0
12+
* Total Accepted: 25.1K
13+
* Total Submissions: 67.6K
14+
* Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'
15+
*
16+
* 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
17+
*
18+
* 示例 1:
19+
*
20+
* 输入:
21+
* [
22+
* ⁠[ 1, 2, 3 ],
23+
* ⁠[ 4, 5, 6 ],
24+
* ⁠[ 7, 8, 9 ]
25+
* ]
26+
* 输出: [1,2,3,6,9,8,7,4,5]
27+
*
28+
*
29+
* 示例 2:
30+
*
31+
* 输入:
32+
* [
33+
* ⁠ [1, 2, 3, 4],
34+
* ⁠ [5, 6, 7, 8],
35+
* ⁠ [9,10,11,12]
36+
* ]
37+
* 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
38+
*
39+
*
40+
*/
41+
func spiralOrder(matrix [][]int) []int {
42+
m := len(matrix)
43+
if m <= 0 {
44+
return []int{}
45+
}
46+
n := len(matrix[0])
47+
if n <= 0 {
48+
return []int{}
49+
}
50+
left, right, up, down := 0, n-1, 0, m-1
51+
ret := make([]int, 0)
52+
for {
53+
// up -> right
54+
for j := left; j <= right;j++ {
55+
ret = append(ret, matrix[up][j])
56+
}
57+
up++
58+
if up > down {
59+
break
60+
}
61+
// right -> down
62+
for i := up; i <= down; i++ {
63+
ret = append(ret, matrix[i][right])
64+
}
65+
right--
66+
if left > right {
67+
break
68+
}
69+
// down -> left
70+
for j := right; j >= left; j-- {
71+
ret = append(ret, matrix[down][j])
72+
}
73+
down--
74+
if up > down {
75+
break
76+
}
77+
// left -> up
78+
for i := down; i >= up; i-- {
79+
ret = append(ret, matrix[i][left])
80+
}
81+
left++
82+
if left > right {
83+
break
84+
}
85+
}
86+
return ret
87+
}
88+

0 commit comments

Comments
 (0)