Spiral Matrix II 解答

Question

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 ]
]

Solution

Similar with Spiral Matrix.

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] result = new int[n][n];
 4         int start = 1, x = 0, y = 0;
 5         int m = n;
 6         while (m > 0) {
 7             if (m == 1) {
 8                 result[x][y] = start;
 9                 break;
10             }
11             for (int i = 0; i < m - 1; i++)
12                 result[x][y++] = start++;
13             for (int i = 0; i < m - 1; i++)
14                 result[x++][y] = start++;
15             for (int i = 0; i < m - 1; i++)
16                 result[x][y--] = start++;
17             for (int i = 0; i < m - 1; i++)
18                 result[x--][y] = start++;
19             x++;
20             y++;
21             m -= 2;
22         }
23         return result;
24     }
25 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4890845.html