Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

C++:
01 void spiralOrderHelper(vector<vector<int>>& matrix, vector<int>& result, int p, int q, int n, int m)
02 {
03     if((p>q)||(n>m))
04         return;
05     for(int i=p;i<=q;i++)
06     {
07         result.push_back(matrix[n][i]);
08     }
09     for(int i=n+1;i<=m;i++)
10     {
11         result.push_back(matrix[i][q]);
12     }
13     if((m==n)||(p==q))
14         return;
15     for(int i=q1;i>=p;i)
16     {
17         result.push_back(matrix[m][i]);
18     }
19     for(int i=m1;i>=n+1;i)
20     {
21         result.push_back(matrix[i][p]);
22     }
23     spiralOrderHelper(matrix,result,p+1,q1,n+1,m1);
24 }
25 class Solution {
26 public:
27     vector<int> spiralOrder(vector<vector<int> > &matrix) {
28         // Start typing your C/C++ solution below
29         // DO NOT write int main() function
30         vector<int> result;
31         int t=matrix.size();
32         if(t==0)
33             return result;
34         int r=matrix[0].size();
35         spiralOrderHelper(matrix,result,0,r1,0,t1);
36         return result;
37     }
38 };
Advertisements
This entry was posted in 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