leetcode 59. Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

思路:一次填充矩阵外围一轮数。

 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int> > res(n, vector<int>(n, 0));
 5         int res[n][n];
 6         int **res = new int* [n];
 7         for (int i = 0; i < n; i++)
 8             
 9         int num = n * n;
10         int cnt = 1;
11         int start_row = 0, start_col = 0, end_row = n - 1, end_col = n - 1; 
12         while (cnt <= num) {
13             for (int j = start_col; j <= end_col; j++) {
14                 res[start_row][j] = cnt++;
15             }
16             for (int i = start_row + 1; i <= end_row; i++) {
17                 res[i][end_col] = cnt++;
18             }
19             for (int j = end_col - 1; j >= start_col; j--) {
20                 res[end_row][j] = cnt++;
21             }
22             for (int i = end_row - 1; i > start_row; i--) {
23                 res[i][start_col] = cnt++;
24             }
25             start_row++;
26             start_col++;
27             end_row--;
28             end_col--;
29         }
30         return res;
31     }
32 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11528539.html