a straight forward implementation of c++


  • 0
    D
      vector<int> spiralOrder(vector<vector<int>>& matrix) {
            
            vector<int> ret;
            int bot = matrix.size()-1;
            if(bot < 0) return ret;
            
            int right   = matrix[0].size() - 1;
            if(right < 0) return ret;
            
            int left  = 0;
            int top   = 0;
           
            int i;
            while(right >=left && bot >=top)
            {
                for(i = left; i <= right; i++)     ret.push_back(matrix[top][i]);
                top++;
    
                for(i = top; i<= bot;i++)          ret.push_back(matrix[i][right]);
                right--;
    
                if (bot >= top) 
                    for(i= right;i>=left;i--)          ret.push_back(matrix[bot][i]);
                bot--;
                
                if(right >= left)
                    for(i = bot;i>=top;i--)           ret.push_back(matrix[i][left]);
                left++;
        
            }
            return ret;
            
            
        }
    

  • 0

    @duoduo Quite intuitive solution, but I think it can be further generalised using states -- here it can be directions as following solution.

    class Solution {
    public:
    	//instead of using several loops for different directions;
    	//using r and c to track the position and steps to track
    	//the maximal steps and using dirs to control directions;
        vector<int> spiralOrder(vector<vector<int>>& matrix) 
        {
            if(matrix.empty()) return vector<int>();
            int dirs[][2]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            int rowSize = matrix.size(), colSize = matrix[0].size();
            int steps[2]{colSize, rowSize-1};
            vector<int> v;
            int r = 0, c = -1, i = 0;
            while(steps[i%2])
            {
                for(int j = 0; j < steps[i%2]; ++j)
                {
                    r += dirs[i][0], c += dirs[i][1];
                    v.push_back(matrix[r][c]);
                }
                steps[i%2]--;
                i = (i+1)%4;
            }
            return v;
        }
    };
    

Log in to reply
 

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