一、题目叙述:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Subscribe to see which companies asked this question.
二、解题思路:
Medium题,这题与54.螺旋矩阵思路基本一致,并且更加简单,思路参考http://blog.youkuaiyun.com/sunshine0_0/article/details/56678002
三、源码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution
{
public int[][] generateMatrix(int n)
{
int[][] res = new int[n][n];
int times = n/2;
int count = 1;
int i,j,k,q,s;
for (i = 0; i < times; i++)
{
for (j = i; j < n - i; j++)
res[i][j] = count++;
for (k = i + 1; k < n - i; k++)
res[k][j - 1] = count++;
for (q = j - 2; q >= i; q--)
res[k-1][q] = count++;
for (s = k - 2; s > i; s--)
res[s][i] = count++;
}
n = n - times * 2;
if (n != 0)
res[times][times] = count;
return res;
}
public static void main(String args[])
{
// int[] digits = {0};
Solution solution = new Solution();
// int[][] abc = {{2,5},{8,4}};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
System.out.print(Arrays.deepToString(solution.generateMatrix(0)));
}
}