挺简单的,不过要考虑边缘情况。注意细节
class Solution {public: vector<vector<int>> generateMatrix(int n) { vector<int> temp(n,0); vector<vector<int>> result; for(int i=0;i<n;i++) result.push_back(temp); int step=n; int direction=0; int startNum=1; int startFirst=0; int startSecond=-1; while(step!=0) { if(direction==0) { startSecond+=1; int temp=step; while(temp--) result[startFirst][startSecond++]=startNum++; startSecond--; direction=1; step--; } else if(direction==1) { startFirst+=1; int temp=step; while(temp--) result[startFirst++][startSecond]=startNum++; startFirst--; direction=2; } else if(direction==2) { startSecond-=1; int temp=step; while(temp--) result[startFirst][startSecond--]=startNum++; startSecond++; direction=3; step--; } else { startFirst-=1; int temp=step; while(temp--) result[startFirst--][startSecond]=startNum++; startFirst++; direction=0; } } return result; }};新闻热点
疑难解答