My C++ solution


  • 0
    C

    Here is my code in C++. I use four variable to solve this problem. Just follow the direction of spiral order.

    vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
            if(matrix.empty()) return result;
            int beginX = 0;
            int beginY = 0;
            int endY = matrix.size()-1;
            int endX = matrix[0].size()-1;
            while(1){
                for(int i=beginX;i<=endX; i++)
                    result.push_back(matrix[beginY][i]);// left to right
                beginY++;
                if(beginY>endY) break;
                
                for(int j=beginY; j<=endY; j++) 
                    result.push_back(matrix[j][endX]); // up to down
                endX--;
                if(beginX>endX) break;
                
                for(int i=endX; i>=beginX; i--)
                    result.push_back(matrix[endY][i]); // right to left
                endY--;
                if(beginY>endY) break;
                
                for(int j=endY; j>=beginY;j--)
                    result.push_back(matrix[j][beginX]);// down to up
                beginX++;
                if(beginX>endX) break;
            }
            return result;
        }

Log in to reply
 

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