-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiral-matrix.cpp
70 lines (62 loc) · 1.32 KB
/
spiral-matrix.cpp
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
69
70
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>> &matrix) {
constexpr int VISITED = 0xff;
enum dir {
RIGHT,
DOWN,
LEFT,
UP,
};
const int M = matrix.size();
const int N = matrix[0].size();
const size_t L = M * N;
enum dir dir = RIGHT;
vector<int> elements;
for (int row = 0, col = 0; elements.size() < L;) {
int &val = matrix[row][col];
if (val != VISITED) {
elements.push_back(val);
val = VISITED;
}
switch (dir) {
case RIGHT:
if (col + 1 >= N || matrix[row][col + 1] == VISITED) {
dir = DOWN;
} else {
++col;
}
break;
case DOWN:
if (row + 1 >= M || matrix[row + 1][col] == VISITED) {
dir = LEFT;
} else {
++row;
}
break;
case LEFT:
if (col - 1 < 0 || matrix[row][col - 1] == VISITED) {
dir = UP;
} else {
--col;
}
break;
case UP:
if (row - 1 < 0 || matrix[row - 1][col] == VISITED) {
dir = RIGHT;
} else {
--row;
}
break;
}
}
return elements;
}
};