classSolution{public:vector<int>spiralOrder(vector<vector<int>>&matrix){vector<int>result;// This will store our spiral elementsintrows=matrix.size();intcols=matrix[0].size();// Check if matrix is emptyif(matrix.empty()){returnresult;}// Set our boundariesinttop=0;// top-most row boundary intbottom=rows-1;// bottom-most row boundaryintleft=0;// left-most column boundaryintright=cols-1;// right-most column boundary// Walk in spiral form, until our boundaries gets crossedwhile(top<=bottom&&left<=right){// 1. Go right (top row)for(intcol=left;col<=right;col++){result.push_back(matrix[top][col]);}top++;// We're done with this top row, move down// 2. Go dowm (right column)for(introw=top;row<=bottom;row++){result.push_back(matrix[row][right]);}right--;// We're done with this right column, move left// 3. Go left (bottom row)// Check: Is there still a bottom row, to go left?if(top<=bottom){for(intcol=right;col>=left;col--){result.push_back(matrix[bottom][col]);}bottom--;// We're done with this bottom row, move up}// 4. Go up (left column)// Check: Is there still a left column, to go up?if(left<=right){for(introw=bottom;row>=top;row--){result.push_back(matrix[row][left]);}left++;// We're done with this left column, move right}}returnresult;}};
classSolution{public:vector<int>spiralOrder(vector<vector<int>>&matrix){vector<int>result;introws=matrix.size();intcols=matrix[0].size();if(matrix.empty()){returnresult;}inttop=0;intbottom=rows-1;intleft=0;intright=cols-1;intdir=0;// This will decide, to which direction we have to go// dir = 0 -> left to right (top)// dir = 1 -> top to bottom (right)// dir = 2 -> right to left (bottom)// dir = 3 -> bottom to top (left)// dir = 4 -> dir = 0while(top<=bottom&&left<=right){// If dir = 0 -> Go left to right (top)if(dir==0){for(intcol=left;col<=right;col++){result.push_back(matrix[top][col]);}top++;// This top-row is done, move inward}// If dir = 1 -> Go top to bottom (right)if(dir==1){for(introw=top;row<=bottom;row++){result.push_back(matrix[row][right]);}right--;// This right-col is done, move inward}// If dir = 2 -> Go right to left (bottom)if(dir==2){for(intcol=right;col>=left;col--){result.push_back(matrix[bottom][col]);}bottom--;// This bottom-row is done, move inward}// If dir = 3 -> Go bottom to top (left)if(dir==3){for(introw=bottom;row>=top;row--){result.push_back(matrix[row][left]);}left++;// This left col is done, move inward}dir++;// Change direction at each// If dir = 4, make dir = 0dir=dir%4;}returnresult;}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?