Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

C++:
01 vector<vector<int> > generateMatrix(int n)
02  {
03       vector<vector<int> > A(n);
04       for(int i=0;i<n;i++){
05           vector<int> a(n);
06           A[i]=a;
07       }
08       int p=n/2;
09       if(n%2)
10           p++;
11       int cur=1;
12       for(int i=0;i<p;i++){
13           int high=i;
14           int low=n1i;
15           int left=i;
16           int right=n1i;
17           for(int j=left;j<=right;j++)
18               A[high][j]=cur++;
19           if(high<low){
20               for(int j=high+1;j<=low;j++)
21                   A[j][right]=cur++;
22           }
23           if(left<right){
24               for(int j=right1;j>=left;j)
25                   A[low][j]=cur++;
26           }
27           if(high<low1){
28               for(int j=low1;j>=high+1;j)
29                   A[j][left]=cur++;
30           }
31       }
32       return A;
33 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s