21 Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        
        vector<int> ans;
        
        if(matrix.empty()) return ans;
        
        int last_row = matrix.size() -1 ;
        int last_col = matrix[0].size() -1 ;
        
        int first_row = 0;
        int first_col = 0;
        
        while(first_row <= last_row && first_col <= last_col)
        {
            printEdges(matrix, ans, first_row,last_row, first_col, last_col);
            
        }
        
        
        return ans;
    }
    
    void printEdges(vector<vector<int>> matrix, vector<int>& ans, int& first_row, int& last_row, int& first_col,  int& last_col)
    {
        //print first row
        for(int i=first_col;i<=last_col; i++) ans.push_back(matrix[first_row][i]);
        
        //if
        if(last_row == first_row);
        else
        {
            //print last column
            for(int i=first_row+1;i<=last_row;i++) ans.push_back(matrix[i][last_col]);
            
            //print last row
            for(int i=last_col-1;i>=first_col;i--) ans.push_back(matrix[last_row][i]);
            
             //if,print first column
            if(last_col == first_col);
            else
            {
                for(int i=last_row-1;i>first_row;i--) ans.push_back(matrix[i][first_col]);
            
            }
            
            first_col++;
            last_row--;
            last_col--;
               
        }
        
        //update pointer
        first_row++;
        
    }
    
};
posted @ 2019-08-22 16:35  孙小鸟  阅读(85)  评论(0编辑  收藏  举报