An idiot way to solve this problem in cpp


  • 0
    B
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if (matrix.empty()) return {};//dont forget the null situation
            int row = matrix.size();
            int col = matrix[0].size();
            int m = row - 1;
            int n = col - 1;
            int x = 0;
            vector<int> res;
            while(m>=0&&n>=0){
                for(int a = 0+x;a<=col-1-x;a++){
                    res.push_back(matrix[0+x][a]);
                }
                if(--m<0) break;//after every loop u need to check whether it can continue or not
                for(int b = 1+x;b<=row-1-x;b++){
                    res.push_back(matrix[b][col-1-x]);
                }
                if(--n<0) break;
                for(int c = col-2-x;c>=0+x;c--){
                    res.push_back(matrix[row-1-x][c]);
                }
                if(--m<0) break;
                
                for(int d = row-2-x;d>=1+x;d--){
                    res.push_back(matrix[d][0+x]);
                }
                if(--n<0) break;
                x++;
            }
            return res;
        }
    };
    

    This solution is a quite direct way to solve this, draw a table and spiral it then you'll figure it out.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.