-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiral_Matrix.cpp
More file actions
68 lines (59 loc) · 1.71 KB
/
Copy pathSpiral_Matrix.cpp
File metadata and controls
68 lines (59 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int row = matrix.size();
int Col = matrix[0].size();
int total = row * Col;
int count = 0;
int sRow = 0;
int sCol = 0;
int eRow = row - 1;
int eCol = Col - 1;
while (count < total) {
for (int i = sCol; i <= eCol && count < total; i++) {
ans.push_back(matrix[sRow][i]);
count++;
}
sRow++;
for (int i = sRow; i <= eRow && count < total; i++) {
ans.push_back(matrix[i][eCol]);
count++;
}
eCol--;
for (int i = eCol; i >= sCol && count < total; i--) {
ans.push_back(matrix[eRow][i]);
count++;
}
eRow--;
for (int i = eRow; i >= sRow && count < total; i--) {
ans.push_back(matrix[i][sCol]);
count++;
}
sCol++;
}
return ans;
}
};
int main() {
Solution sol;
int rows, cols;
cout << "Enter number of rows and columns: ";
cin >> rows >> cols;
vector<vector<int>> matrix(rows, vector<int>(cols));
cout << "Enter matrix elements:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
vector<int> result = sol.spiralOrder(matrix);
cout << "Spiral Order Traversal: ";
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}