https://leetcode.com/problems/spiral-matrix-ii/
#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <vector> #include <map> #include <iostream> using namespace std; class Solution { public: vector< vector<int> > generateMatrix(int n) { int mtx[n][n]; int left=0,right=n,up=0,down=n; int cnt=1; while(cnt <= n*n) { for(int i=left; i<right; i++) mtx[up][i] = cnt, cnt++; if(cnt > n*n)break; for(int i=up+1; i<down; i++) mtx[i][right-1] = cnt, cnt++; if(cnt > n*n)break; for(int i=right-2;i>=left;i--) mtx[down-1][i] = cnt, cnt++; if(cnt > n*n) break; for(int i=down-2; i>up; i--) mtx[i][left] = cnt , cnt ++; left++,up++; down--,right--; } vector < vector<int> >ret; for(int i=0;i<n;i++) { vector <int> iv; for(int j=0;j<n;j++) iv.push_back(mtx[i][j]);//, cout << mtx[i][j] << "*, "; ret.push_back(iv); } return ret; } }; int main() { int n; while(cin >> n) { Solution s; vector < vector<int> > ivec = s.generateMatrix(n); for(int i=0;i<ivec.size();i++) { for(int j=0;j<ivec[0].size();j++) cout << ivec[i][j] << ","; cout << endl; } } return 0; }