Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spiral Matrix #1726

Merged
merged 1 commit into from
Oct 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Program's_Contributed_By_Contributors/C++/spiralMatrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {

vector<int> ans;
int row = matrix.size(); //?
int col = matrix[0].size();

// These are indexes--->
int startingRow = 0;
int endingCol = col - 1;
int endingRow = row - 1;
int startingCol = 0;

int count = 0;
int total = row * col;
while (count < total)
{
// Printing Starting row:
for (int index = startingCol; count < total && index <= endingCol; index++)
{
ans.push_back(matrix[startingRow][index]);
count++;
}
startingRow++;

// Printing ending column:
for (int index = startingRow; count < total && index <= endingRow; index++)
{
ans.push_back(matrix[index][endingCol]);
count++;
}
endingCol--;

// Printing ending row:
for (int index = endingCol; count < total && index >= startingCol; index--)
{
ans.push_back(matrix[endingRow][index]);
count++;
}
endingRow--;

// Printing starting column:
for (int index = endingRow; count < total && index >= startingRow; index--)
{
ans.push_back(matrix[index][startingCol]);
count++;
}
startingCol++;
}

return ans;
}
};