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 vector<int> spiralOrder(vector<vector<int> > &matrix)
02 {
03       vector<int> result;
04       int m=matrix.size();
05       if(m==0)
06           return result;
07       int n=matrix[0].size();
08       if(n==0)
09           return result;
10       int l=m<n?m:n;
11       int p;
12       if(l%2)
13           p=l/2+1;
14       else
15           p=l/2;
16       for(int i=0;i<p;i++){
17           int high=i;
18           int left=i;
19           int low=m1i;
20           int right=n1i;
21           for(int j=left;j<=right;j++)
22               result.push_back(matrix[high][j]);
23           if(high<low){
24               for(int j=high+1;j<=low;j++)
25                 result.push_back(matrix[j][right]);
26           }
27           if((high<low)&&(left<right)){
28               for(int j=right1;j>=left;j)
29                   result.push_back(matrix[low][j]);
30           }
31           if((left<right)&&(high<low1)){
32               for(int j=low1;j>=high+1;j)
33                   result.push_back(matrix[j][left]);
34           }
35        }
36        return result;
37 }
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