# Share my 0 ms C++ clear and easy to understand

• ``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> ret;
if (!matrix.size())return ret;
int direc = 1;
set<pair<int, int>> exist;
pair<int, int> start{ 0, 0 };
direction(matrix, direc, exist, start, ret);
return ret;

}
void direction(vector<vector<int>>& matrix, int &direc, set<pair<int, int>> &exist, pair<int, int> &start, vector<int>& ret)
{
if (start.first>int(matrix.size()) - 1 || start.second>int(matrix[0].size()) - 1 || exist.count(start))
return;
int j = 0;
switch (direc)
{
case 1: //east

for (j = start.second; j<matrix[0].size() && !exist.count(make_pair(start.first, j)); j++)
{
ret.push_back(matrix[start.first][j]);
exist.insert(make_pair(start.first, j));
}
direc = 2;
start = make_pair(start.first + 1, j - 1);
direction(matrix, direc, exist, start, ret);
break;
case 2://south

for (j = start.first; !exist.count(make_pair(j, start.second)) && j<matrix.size(); j++)
{
ret.push_back(matrix[j][start.second]);
exist.insert(make_pair(j, start.second));
}
direc = 3;
start = make_pair(j - 1, start.second - 1);
direction(matrix, direc, exist, start, ret);
break;

case 3://west

for (j = start.second; !exist.count(make_pair(start.first, j)) && j >= 0; j--)
{
ret.push_back(matrix[start.first][j]);
exist.insert(make_pair(start.first, j));
}
direc = 4;
start = make_pair( start.first - 1,j+1);
direction(matrix, direc, exist, start, ret);
break;

case 4://north

for (j = start.first; !exist.count(make_pair(j, start.second)) && j >= 0; j--)
{
ret.push_back(matrix[j][start.second]);
exist.insert(make_pair(j, start.second));
}
direc = 1;
start = make_pair(j + 1, start.second + 1);
direction(matrix, direc, exist, start, ret);
break;
}
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.