Leetcode: Spiral Matrix II

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 ]

]

Spiral Matrix一样的处理,甚至还简单一些,这个确定是方阵。分层,然后按照上右下左的顺序放入数组中。每个元素只访问一次,时间复杂度是O(n^2)。

 1 public class Solution {

 2     public int[][] generateMatrix(int n) {

 3         int[][] res = new int[n][n];

 4         if (n < 0) return null;

 5         int levelNum = n / 2;

 6         int count = 1;

 7         for (int level=0; level<levelNum; level++) {

 8             for (int i=level; i<n-1-level; i++) {

 9                 res[level][i] = count++;

10             }

11             for (int i=level; i<n-1-level; i++) {

12                 res[i][n-1-level] = count++;

13             }

14             for (int i=n-1-level; i>level; i--) {

15                 res[n-1-level][i] = count++;

16             }

17             for (int i=n-1-level; i>level; i--) {

18                 res[i][level] = count++;

19             }

20         }

21         if (n % 2 == 1) {

22             res[levelNum][levelNum] = count;

23         }

24         return res;

25     }

26 }

 

你可能感兴趣的:(LeetCode)