Spiral Matrix LeetCode solution in C++
1class Solution {2public:3vector<int> _res;4vector<vector<bool>> _visited;56void spin(vector<vector<int>> &matrix, int direction, int i, int j) {7_visited[i][j] = true;8_res.push_back(matrix[i][j]);910switch (direction) {11// left to right12case 0:13if (j + 1 >= matrix[0].size() || _visited[i][j + 1]) {14direction = 1;15i++;16} else {17j++;18}19break;20// up to bottom21case 1:22if (i + 1 >= matrix.size() || _visited[i + 1][j]) {23direction = 2;24j--;25} else {26i++;27}28break;29// right to left30case 2:31if (j == 0 || _visited[i][j - 1]) {32direction = 3;33i--;34} else {35j--;36}37break;38// bottom to up39case 3:40if (i == 0 || _visited[i - 1][j]) {41direction = 0;42j++;43} else {44i--;45}46break;47}48if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size()) {49return;50}51if (_visited[i][j]) {52return;53}54spin(matrix, direction, i, j);55}5657vector<int> spiralOrder(vector<vector<int>> &matrix) {58_res.clear();59_visited = vector<vector<bool>>(matrix.size(), std::vector<bool>(matrix[0].size(), false));60spin(matrix, 0, 0, 0);61return _res;62}63};