Iteration c++ solution whitch takes just 0ms


  • 0
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
            if(matrix.size()==0)return result;
            int tx=0,ty=0;
            int rx=matrix.size()-1,ry=matrix[0].size()-1;
            while(tx<=rx&&ty<=ry){
                if(tx==rx){
                    for(int i=ty;i<=ry;i++)
                        result.push_back(matrix[tx][i]);
                }
                else if(ty==ry&&rx!=0){
                    for(int i=tx;i<=rx;i++)
                        result.push_back(matrix[i][ty]);
                }
                else{
                    int curx=tx,cury=ty;
                    while(cury!=ry)
                        result.push_back(matrix[tx][cury]),cury++;
                    while(curx!=rx)
                        result.push_back(matrix[curx][ry]),curx++;
                    while(cury!=ty)
                        result.push_back(matrix[rx][cury]),cury--;
                    while(curx!=tx)
                        result.push_back(matrix[curx][ty]),curx--;
                }
                tx++,ty++,rx--,ry--;
            }
            return result;
        }
    };

Log in to reply
 

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