diff --git a/54_spiral_matrix/main.cpp b/54_spiral_matrix/main.cpp new file mode 100644 index 0000000..f4f1979 --- /dev/null +++ b/54_spiral_matrix/main.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +class Solution { + private: + // {row, col} + const vector> directions{ + {0, 1}, + {1, 0}, + {0, -1}, + {-1, 0}, + }; + + inline pair addPair(const pair& x, const pair& y) { + return {x.first + y.first, x.second + y.second}; + } + + void nextDirection(int& index, pair& direction) { + if (++index >= 4) index = 0; + direction = directions[index]; + } + + public: + vector spiralOrder(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + + vector result; + + vector> visited(m + 2, vector(n + 2, false)); + for (int i = 0; i < m + 2; i++) + visited[i][0] = true, visited[i][n + 1] = true; + for (int i = 0; i < n + 2; i++) + visited[0][i] = true, visited[m + 1][i] = true; + + int directionIndex = 0; + pair direction = directions[directionIndex]; + + pair currentPos{1, 1}; + + for (int i = 0; i < m * n; i++) { + auto nextPos = addPair(currentPos, direction); + if (visited[nextPos.first][nextPos.second]) { + nextDirection(directionIndex, direction); + nextPos = addPair(currentPos, direction); + } + visited[currentPos.first][currentPos.second] = true; + result.emplace_back(matrix[currentPos.first - 1][currentPos.second - 1]); + currentPos = nextPos; + } + + return result; + } +};