spiral-matrix 1.0.0
Spiral Matrix
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 vector<int> spiralOrder(vector<vector<int>>& matrix)
9 {
10 if (matrix.empty() || matrix[0].empty()) return {};
11
12 vector<int> answer;
13 answer.reserve((int)(matrix.size() * matrix[0].size()));
14 int m = (int)matrix.size(), n = (int)matrix[0].size();
15
16 int left = 0, right = n - 1, top = 0, bottom = m - 1;
17 while (left <= right && top <= bottom)
18 {
19 for (int j = left; j <= right; ++j)
20 answer.push_back(matrix[top][j]);
21 ++top;
22
23 for (int i = top; i <= bottom; ++i)
24 answer.push_back(matrix[i][right]);
25 --right;
26
27 if (top <= bottom)
28 {
29 for (int j = right; j >= left; --j)
30 answer.push_back(matrix[bottom][j]);
31 --bottom;
32 }
33
34 if (left <= right)
35 {
36 for (int i = bottom; i >= top; --i)
37 answer.push_back(matrix[i][left]);
38 ++left;
39 }
40 }
41
42 return answer;
43 }
44};
45
46int main()
47{
48 vector<vector<int>> matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
49 vector<int> answer = Solution().spiralOrder(matrix);
50 for (int element: answer)
51 cout << element << " ";
52 cout << endl;
53 return 0;
54}
vector< int > spiralOrder(vector< vector< int > > &matrix)
Definition main.cpp:8
int main()
Definition main.cpp:46