sourcecode

Thursday, January 3, 2013

Spiral Matrix


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 {//two ways. auxillary road map
//or compute the iteration loop
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> r;//result
        if (matrix.empty() || matrix[0].empty()) return r;
        int const m_max = matrix.size();//rows
        int const n_max = matrix[0].size();//cols
        int dec = 0;//decrement count
        int row = 0;//start row
        int col = 0;//start col
        int lastIndex = 0;
        while(1){
            lastIndex = n_max-1 -dec + col;
            for(int ii = col; ii <= lastIndex; ++ii){//left to right
                r.push_back(matrix[row][ii]);
            }
            col = lastIndex;
            ++row;
            ++dec;
            if (dec >= m_max) return r;
            
            lastIndex = m_max-1 -dec + row;
            for(int ii = row; ii <= lastIndex; ++ii){//up to down
                r.push_back(matrix[ii][col]);
            }
            row = lastIndex;
            --col;
            if (dec >= n_max) return r;
            
            lastIndex = col - (n_max-1-dec);
            for(int ii = col; ii >= lastIndex; --ii){//right to left
                r.push_back(matrix[row][ii]);
            }
            col = lastIndex;
            --row;
            ++dec;
            if (dec >= m_max) return r;
            
            lastIndex = dec + row + 1 - m_max;
            for(int ii = row; ii >= lastIndex; --ii){//down to up
                r.push_back(matrix[ii][col]);
            }
            row = lastIndex;
            ++col;
            if (dec >= n_max) return r;
        }
        return r;
    }
};

No comments: