easy to understand C++


  • 0
    K

    the basic idea is that we create 2D vector to mark number that have been visited.

    vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if(matrix.empty()||matrix[0].empty())return {};
            int m=matrix.size(),n=matrix[0].size();
            vector<int>res;
            vector<vector<bool>>vis(m,vector<bool>(n,false));
            int i=0,j=0;
            res.push_back(matrix[0][0]);
            vis[0][0]=true;
            while(res.size()<m*n)
            {
                while(j+1<n && !vis[i][j+1])
                {
                    res.push_back(matrix[i][++j]);
                    vis[i][j]=true;
                }
                while(i+1<m && !vis[i+1][j])
                {
                    res.push_back(matrix[++i][j]);
                    vis[i][j]=true;
                }
                
                while(j-1>=0 && !vis[i][j-1])
                {
                    res.push_back(matrix[i][--j]);
                    vis[i][j]=true;
                }
                while(i-1>=0 && !vis[i-1][j])
                {
                    res.push_back(matrix[--i][j]);
                    vis[i][j]=true;
                }
            }
            return res;
        }
    

Log in to reply
 

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