Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 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 void generateMatrixHelper(vector<vector<int>>& result,
02                           int p, int q, int m, int n, int& t)
03 {
04     if((p>q)||(m>n))
05         return;
06     for(int i=p;i<=q;i++)
07     {
08         result[m][i]=t++;
09     }
10     for(int i=m+1;i<=n;i++)
11     {
12         result[i][q]=t++;
13     }
14     for(int i=q1;i>=p;i)
15     {
16         result[n][i]=t++;
17     }
18     for(int i=n1;i>m;i)
19     {
20         result[i][p]=t++;
21     }
22     generateMatrixHelper(result,p+1,q1,m+1,n1,t);
23 }
24 
25 class Solution {
26 public:
27     vector<vector<int> > generateMatrix(int n) {
28         // Start typing your C/C++ solution below
29         // DO NOT write int main() function
30         vector<vector<int>> result(n);
31         int t=1;
32         for(int i=0;i<n;i++)
33         {
34             for(int j=0;j<n;j++)
35                 result[i].push_back(0);
36         }
37         generateMatrixHelper(result,0,n1,0,n1,t);
38         return result;
39     }
40 };
Advertisements
This entry was posted in Array and linked list, Recursive. 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