给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
1 #include<vector> 2 #include <iostream> 3 #include<algorithm> 4 #include <numeric> 5 #include<iterator> 6 using namespace std; 7 8 class Solution { 9 public: 10 vector<vector<int>> generateMatrix(int n) { 11 vector<vector<int>> res(n, vector<int>(n, 0)); // 使用vector定义一个二维数组 12 int t = 0; 13 int r = n - 1; 14 int b = n - 1; 15 int l = 0; 16 int k = 1; 17 while (k <= n * n) 18 { 19 for (int i = l; i <= r; i++, k++) { 20 res[t][i] = k; 21 } 22 t++; 23 for (int i = t; i <= b; i++, k++) { 24 res[i][r] = k; 25 } 26 r--; 27 for (int i = r; i >= l; i--, k++) { 28 res[b][i] = k; 29 } 30 b--; 31 for (int i = b; i >= t; i--, k++) { 32 res[i][l] = k; 33 } 34 l++; 35 } 36 return res; 37 } 38 }; 39 int main() { 40 vector<vector<int>> res(3, vector<int>(3, 0)); 41 //vector<int> res; 42 Solution a; 43 res = a.generateMatrix(3); 44 for (const auto& i : res) { 45 for (auto j : i) { 46 cout << j <<endl; 47 } 48 } 49 }
标签:59,int,res,矩阵,++,II,--,vector,include From: https://www.cnblogs.com/lihaoxiang/p/16972173.html