0% found this document useful (0 votes)
2 views2 pages

Spiral Matrix

The document contains a C++ class named 'Solution' with a method 'spiralOrder' that extracts elements from a 2D matrix in a spiral order. It uses a vector to store the result and modifies the matrix by setting visited elements to INT_MAX. The method continues until all elements are processed, ensuring no duplicates are added to the result.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Spiral Matrix

The document contains a C++ class named 'Solution' with a method 'spiralOrder' that extracts elements from a 2D matrix in a spiral order. It uses a vector to store the result and modifies the matrix by setting visited elements to INT_MAX. The method continues until all elements are processed, ensuring no duplicates are added to the result.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//changing the value to INT_MAX is a bit unorthodox and is not appreciated

//but hey its working fine

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int hor=matrix[0].size();
int ver=matrix.size()-1;
int a = -1,b = 0;
int flag1=0,flag2=0,flag3=0,flag4=0;
while(hor!=0 || ver!=0){
if(hor!=0){
a++;
for(int i=0;i<hor;i++){
if(matrix[b][a]!=INT_MAX)
res.push_back(matrix[b][a]);
matrix[b][a]=INT_MAX;
a++;
}
a--;
hor--;
}
if(hor==0 && ver==0) break;
if(ver!=0){
b++;
for(int i = 0;i<ver;i++){
if(matrix[b][a]!=INT_MAX)
res.push_back(matrix[b][a]);
matrix[b][a]=INT_MAX;
b++;
}
b--;
ver--;
}
if(hor==0 && ver==0) break;
if(hor!=0){
a--;
for(int i=0;i<hor;i++){
if(matrix[b][a]!=INT_MAX)
res.push_back(matrix[b][a]);
matrix[b][a]=INT_MAX;
a--;
}
a++;
hor--;
}
if(hor==0 && ver==0) break;
if(ver!=0){
b--;
for(int i = 0;i<ver;i++){
if(matrix[b][a]!=INT_MAX)
res.push_back(matrix[b][a]);
matrix[b][a]=INT_MAX;
b--;
}
b++;
ver--;
}
}
return res;
}
};

You might also like