Monday, 1 August 2016

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].


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        int m = matrix.size();
        if(m == 0){
            return result;
        }
        int n = matrix[0].size();
        int dir = 0;  
        int top = 0, bottom = m - 1, left = 0, right = n - 1;
        
        while(top <= bottom && left <= right){  
         if(dir == 0){  
           for(int i = left; i <= right; i++){  
             result.push_back(matrix[top][i]);  
           }
           top++;  
           dir = 1;  
         }  
         else if(dir == 1){
           for(int i = top; i <= bottom; i++){  
             result.push_back(matrix[i][right]);  
           }  
           right--;  
           dir = 2;  
         }  
         else if(dir == 2){  
           for(int i = right; i >= left; i--){  
             result.push_back(matrix[bottom][i]);
           }  
           bottom--;  
           dir = 3;  
         }else{  
           for(int i = bottom; i >= top; i--){  
             result.push_back(matrix[i][left]);  
           }  
           left++;  
           dir = 0;  
         }  
       }  
       return result;
    }
};
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts