题目描述:

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是一样的,而且col和row相同的情况反而更简单了。

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int>> ret(n, vector<int>(n, 1));
 5         int val = 1, times = n/2;
 6         for(int i = 0; i < times; i++){
 7             for(int j = i; j < n-1-i; j++)
 8                 ret[i][j] = val++;
 9             for(int j = i; j < n-1-i; j++)
10                 ret[j][n-1-i] = val++;
11             for(int j = n-1-i; j > i; j--)
12                 ret[n-1-i][j] = val++;
13             for(int j = n-1-i; j > i; j--)
14                 ret[j][i] = val++;
15         }
16         if(n%2 == 1)
17             ret[times][times] = val;
18         return ret;
19     }
20 };

 

 

 

posted on 2018-03-05 08:33  宵夜在哪  阅读(100)  评论(0编辑  收藏  举报