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 ]
]
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
以这种方式进行循环即可。
 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int[][] result = new int[n][n];
 5         int a = 1;
 6         int top = 0;
 7         int bot = n - 1;
 8         int left = 0;
 9         int right = n - 1;
10         while(top < bot && left < right){
11             for(int i = left; i < right; i ++)
12             {
13                 result[top][i] = a ++;
14             }
15             for(int i = top; i < bot; i ++)
16             {
17                 result[i][right] = a ++;
18             }
19             for(int i = right; i > left; i --)
20             {
21                 result[bot][i] = a ++;
22             }
23             for(int i = bot; i > top; i --)
24             {
25                 result[i][left] = a ++;    
26             }
27             top ++;
28             bot --;
29             left ++;
30             right --;
31         }
32         if(top == bot && left == right){//对于n 为奇数的情况。
33             result[top][left] = a;
34         }
35         return result;
36     }
37 }

 第三遍:

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] result = new int[n][n];
 4         if(n == 0) return result;
 5         int top = 0, bot = n - 1, num = 1;
 6         while(top < bot){
 7             for(int i = top; i < bot; i ++)
 8                 result[top][i] = num ++;
 9             for(int i = top; i < bot; i ++)
10                 result[i][bot] = num ++;
11             for(int i = bot; i > top; i --)
12                 result[bot][i] = num ++;
13             for(int i = bot; i > top; i --)
14                 result[i][top] = num ++;
15             top ++; bot --;
16         }
17         if(top == bot) result[top][bot] = num;
18         return result;
19     }
20 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3351225.html