Sharing my fast C++ solution


  • 0
    T
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            int m = matrix.size();
            if(m==0)
                return (vector<int>(0));
            int n = matrix[0].size();
            if(n==0)
                return (vector<int>(0));
                
            vector<int> result;
            vector<vector<bool>> visited(m, vector<bool>(n, false));
            
            int i=0, j=0, direction=0;
            while(true)
            {
                result.push_back(matrix[i][j]);
                visited[i][j] = true;
                int nexti, nextj;
                if(direction==0)
                {
                    nexti = i;
                    nextj = j+1;
                }
                else if(direction==1)
                {
                    nexti = i + 1;
                    nextj = j;
                }
                else if(direction==2)
                {
                    nexti = i;
                    nextj = j - 1;
                }
                else
                {
                    nexti = i-1;
                    nextj = j;
                }
                
                if(nexti>=0 && nexti<m && nextj>=0 && nextj<n && visited[nexti][nextj]==false)
                {
                    i = nexti;
                    j = nextj;
                }
                else // redirect
                {
                    direction = (direction+1)%4;
                    if(direction==0)
                        j++;
                    else if(direction==1)
                        i++;
                    else if(direction==2)
                        j--;
                    else
                        i--;
                    if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==true)
                        break;
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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