Thursday, January 29, 2015

54 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].
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        int m= matrix.size();
        if (m<=0)
            return res;
        int n = matrix[0].size();
        if (n<=0)
            return res;
            
        int left = 0,right = n-1;
        int up=0,down=m-1;
        while(left<=right && up<=down)
        {
            for (int j=left;j<=right;j++)
            {
                res.push_back(matrix[up][j]);
            }
            up++;
            for (int i=up;i<=down;i++)
            {
                res.push_back(matrix[i][right]);
            }
            right--;
            if (up<=down)
            {
                for (int j=right;j>=left;j--)
                {
                    res.push_back(matrix[down][j]);
                }
            }
            down--;
            if (left<=right)
            {
                for (int i=down;i>=up;i--)
                {
                    res.push_back(matrix[i][left]);
                }
            }
            left++;
        }
        return res;
    }
};

No comments:

Post a Comment