@@ -4,40 +4,64 @@ using namespace std;
44
55class Solution {
66 public:
7- vector<int > spiralOrder (vector<vector<int >> & matrix) {
7+ vector<int > spiralOrder (const vector<vector<int >>& matrix) {
88 vector<int > res;
9- if (matrix.empty ()) return res;
9+ if (matrix.empty ()) {
10+ return res;
11+ }
1012 res.reserve (matrix.size () * matrix[0 ].size ());
11- int top = 0 , left = 0 , bottom = matrix.size () - 1 , right = matrix[0 ].size () - 1 ;
12- auto cur = 0 ;
13- while (bottom >= top || right >= left) {
14- if (bottom >= top) {
15- for (cur = left; cur <= right; ++cur) res.push_back (matrix[top][cur]);
13+ int64_t top = 0 , lft = 0 , bot = matrix.size () - 1 , rgt = matrix[0 ].size () - 1 ;
14+ int64_t cur = 0 ;
15+ while (bot >= top || rgt >= lft) {
16+ if (bot >= top) {
17+ for (cur = lft; cur <= rgt; ++cur) {
18+ res.push_back (matrix[top][cur]);
19+ }
1620 }
1721 ++top;
18- if (right >= left) {
19- for (cur = top; cur <= bottom; ++cur) res.push_back (matrix[cur][right]);
22+ if (rgt >= lft) {
23+ for (cur = top; cur <= bot; ++cur) {
24+ res.push_back (matrix[cur][rgt]);
25+ }
2026 }
21- --right;
22- if (bottom >= top) {
23- for (cur = right; cur >= left; --cur) res.push_back (matrix[bottom][cur]);
27+ --rgt;
28+ if (bot >= top) {
29+ for (cur = rgt; cur >= lft; --cur) {
30+ res.push_back (matrix[bot][cur]);
31+ }
2432 }
25- --bottom;
26- if (right >= left) {
27- for (cur = bottom; cur >= top; --cur) res.push_back (matrix[cur][left]);
33+ --bot;
34+ if (rgt >= lft) {
35+ for (cur = bot; cur >= top; --cur) {
36+ res.push_back (matrix[cur][lft]);
37+ }
2838 }
29- ++left ;
39+ ++lft ;
3040 }
3141 return res;
3242 }
3343};
3444
35- int main (int argc, char const * argv[]) {
45+ int main (int argc, char const * argv[]) {
3646 Solution solution;
37- vector<vector<int >> matrix0{{1 , 1 , 1 , 1 , 1 }, {2 , 2 , 2 , 2 , 2 }, {3 , 3 , 3 , 3 , 3 }, {4 , 4 , 4 , 4 , 4 }};
38- vector<vector<int >> matrix1{{1 }, {2 }, {3 }, {4 }};
47+ vector<vector<int >> matrix0{
48+ {1 , 1 , 1 , 1 , 1 },
49+ {2 , 2 , 2 , 2 , 2 },
50+ {3 , 3 , 3 , 3 , 3 },
51+ {4 , 4 , 4 , 4 , 4 },
52+ };
53+ vector<vector<int >> matrix1{
54+ {1 },
55+ {2 },
56+ {3 },
57+ {4 },
58+ };
3959
40- for (auto &&value : solution.spiralOrder (matrix0)) { cout << value << " " ; }
60+ for (auto && value : solution.spiralOrder (matrix0)) {
61+ cout << value << " " ;
62+ }
4163 cout << endl;
42- for (auto &&value : solution.spiralOrder (matrix1)) { cout << value << " " ; }
64+ for (auto && value : solution.spiralOrder (matrix1)) {
65+ cout << value << " " ;
66+ }
4367}
0 commit comments