Monday, November 25, 2013

LeetCode Problem : Spiral Matrix

Problem


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

Code


vector<int> spiralOrder(vector<vector<int> > &matrix) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int m = matrix.size();
    vector<int> result;
    if(m == 0)
        return result;
    int n = matrix[0].size();
    int num = max(m,n);
    int i = 0,j = 0;

    while(i < (m + 1)/2 && j < (n + 1)/2){
        for(int k = j; k <= n - 1 - j; ++k)
            result.push_back(matrix[i][k]);
        for(int k = i + 1; k < m - 1 - i; ++k)
            result.push_back(matrix[k][n - 1 - j]);
        if(m - 1 - i != i){
            for(int k = n - 1 - j; k >= j; --k)
                result.push_back(matrix[m - 1 - i][k]);
        }
        if(n - 1 - j != j){
            for(int k = m - 2 - i; k > i; --k)
                result.push_back(matrix[k][j]);
        }
        ++i;++j;
    }
    return result;
}

No comments:

Post a Comment