# It is my clear solution

• ``````class Solution {public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
int m = matrix.size();
if(m==0){
return vector<int>();
}
int n = matrix[0].size();
vector<int> result;
vector<vector<int>> hash_result(m, vector<int>(n,-1));
dfs(0,0,matrix,hash_result,m,n,result,0);
return result;
}
void dfs(int x, int y, vector<vector<int>> &matrix, vector<vector<int>> &hash,int m,int n,vector<int>& result,int direction){
result.push_back(matrix[x][y]);
hash[x][y] = 0;
switch(direction){
case 0:
{
if(y+1 < n && hash[x][y+1] == -1)
dfs(x,y+1,matrix,hash,m,n,result,0);
else if(x+1 < m && hash[x+1][y] == -1)
dfs(x+1,y,matrix,hash,m,n,result,1);
break;
}
case 1:
{
if(x+1 < m && hash[x+1][y] == -1)
dfs(x+1,y,matrix,hash,m,n,result,1);
else if(y-1 >= 0 && hash[x][y-1] == -1)
dfs(x,y-1,matrix,hash,m,n,result,2);
break;
}
case 2:
{
if(y-1 >= 0 && hash[x][y-1] == -1)
dfs(x,y-1,matrix,hash,m,n,result,2);
else if(x - 1 >= 0 && hash[x-1][y] == -1)
dfs(x-1,y,matrix,hash,m,n,result,3);
break;
}
case 3:
{
if(x-1 >= 0 && hash[x-1][y]==-1)
dfs(x-1,y,matrix,hash,m,n,result,3);
else if(y+1 < n && hash[x][y+1] == -1)
dfs(x,y+1,matrix,hash,m,n,result,0);
break;
}
}

}
``````

};

• use hash to store the i,j which have been step over, direction (0,1,2,3) means right,down,left,up.

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