LeetCode OJ 59. 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不同,这个题目要求生成一个方阵,方阵的值是螺旋递增的。


【思路】

其实这个题目与上一个大同小异,他们遍历矩阵的顺序是相同的,只要把取值变为赋值就可以了。


【java代码】

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] matrix = new int[n][n];
 4 
 5         int top = 0;
 6         int bottom = n-1;
 7         int left = 0;
 8         int right = n-1;
 9         int num = 1;
10 
11         while(true){
12             for(int i = left; i <= right; i++) matrix[top][i] = num++;
13             top++;
14             if(left > right || top > bottom) break;
15 
16             for(int i = top; i <= bottom; i++) matrix[i][right] = num++;
17             right--;
18             if(left > right || top > bottom) break;
19 
20             for(int i = right; i >= left; i--) matrix[bottom][i] = num++;
21             bottom--;
22             if(left > right || top > bottom) break;
23 
24             for(int i = bottom; i >= top; i--) matrix[i][left] = num++;
25             left++;
26             if(left > right || top > bottom) break;
27         }
28 
29         return matrix;
30     }
31 }
原文地址:https://www.cnblogs.com/liujinhong/p/5532439.html