Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8963130

Browse files
螺旋矩阵 II
1 parent 8b5ee67 commit 8963130

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.leetcode_cn.medium;
2+
3+
/*************螺旋矩阵 II***********/
4+
/**
5+
* 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
6+
*
7+
* 示例:
8+
*
9+
* 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
10+
*
11+
* @author ffj
12+
*
13+
*/
14+
public class SpiralMatrixII {
15+
16+
public static void main(String[] args) {
17+
int n = 3;
18+
System.out.println(new SpiralMatrixII().generateMatrix(n));
19+
}
20+
21+
public int[][] generateMatrix(int n) {
22+
int[][] result = new int[n][n];
23+
int up = 0, down = n - 1, left = 0, right = n - 1, num = 1;
24+
while (up <= down || right >= left) {
25+
if (left > right) // 判断是否越界
26+
break;
27+
// left -> right
28+
for (int i = left; i <= right; i++)
29+
result[up][i] = num++;
30+
right--;
31+
if ((up + 1) > down)
32+
break;
33+
// up -> down
34+
for (int i = up + 1; i <= down; i++)
35+
result[i][right + 1] = num++;
36+
down--;
37+
if (left > right) // 判断是否越界
38+
break;
39+
// right -> left
40+
for (int i = right; i >= left; i--)
41+
result[down + 1][i] = num++;
42+
left++;
43+
if ((up + 1) > down)
44+
break;
45+
// down -> up
46+
for (int i = down; i >= up + 1; i--)
47+
result[i][left - 1] = num++;
48+
up++;
49+
}
50+
return result;
51+
}
52+
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /