p59

LeetCode p59 Spiral Matrix II 题解

1.题目:

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

题意:

输入一个数n,返回n*n的数组,内容是1-n的螺旋排列。

2.解题思路:

见代码TUT。。暴力了一波。

3.代码


[title] [] [url] [link text]
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
 
public class Solution {
public int[][] generateMatrix(int n) {
int sum = n * n;
int i=0;
int j=0;
int[][] ans = new int[n][n];
for (int k = 1; k <= sum; ) {

while (i<n)
{
if (ans[j][i]!=0) break;
ans[j][i]=k;
//System.out.println(k);
k++;
i++;
}
i--;
j++;
while (j<n)
{
if (ans[j][i]!=0) break;
ans[j][i]=k;
//System.out.println(k);
k++;
j++;
}
i--;
j--;
while (i>-1)
{
if (ans[j][i]!=0) break;
ans[j][i]=k;
//System.out.println(k);
k++;
i--;
}
i++;
j--;
while (j>-1)
{
//System.out.println(i+" "+j);
if (ans[j][i]!=0) break;
//System.out.println(k);
ans[j][i]=k;
k++;
j--;
}
i++;
j++;
//System.out.println(i+" "+j);
}
return ans;
}
}


4.一些总结: