标签:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Array
#include<iostream> #include<vector> using namespace std; vector<vector<int> > generateMatrix(int n) { vector<vector<int> >last_result; vector<int> temp; if(n<=0) return last_result; if(n==1) { temp.push_back(1); last_result.push_back(temp); return last_result; } for(int j=0;j<n;j++) temp.push_back(0); for(int i=0;i<n;i++) last_result.push_back(temp); int quan=n; int start_quan=1; int x1=0,x2=0; int y1=0,y2=n-1; int m1=n-1,m2=n-1; int n1=n-1,n2=0; while(quan>0) { for(int i=x2;i<=x2+quan-2;i++) { last_result[x1][i]=start_quan; start_quan++; } for(int i=y1;i<=y1+quan-2;i++) { last_result[i][y2]=start_quan; start_quan++; } for(int i=m2;i>=m2-(quan-2);i--) { last_result[m1][i]=start_quan; start_quan++; } for(int i=n1;i>=n1-(quan-2);i--) { last_result[i][n2]=start_quan; start_quan++; } quan-=2; x1++;x2++; y1++;y2--; m1--;m2--; n1--;n2++; if(quan==1) { last_result[x1][x2]=start_quan; break; } } return last_result; } int main() { vector<vector<int> > vec; int n=4; vec=generateMatrix(n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) cout<<vec[i][j]<<‘ ‘; cout<<endl; } }
leetcode_59题——Spiral Matrix II(数组)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4545790.html