您的位置:首页 > 其它

leetcode 53: Spiral Matrix

2015-07-28 19:15 405 查看
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.empty())
return res;
int m=matrix.size();
int n=matrix[0].size();
int time=0,start=0;
while(time!=m*n)
{
for(int i=start;i<n-start;i++)
{
res.push_back(matrix[start][i]);
time++;
}
for(int i=start+1;i<m-start;i++)
{
res.push_back(matrix[i][n-start-1]);
time++;
}
//do next step only if the numbers are not in a horizontal line
for(int i=n-start-2;i>=start&&m-start-1>start;i--)
{
res.push_back(matrix[m-start-1][i]);
time++;
}
//do next step only if the numbers are not in a vertical line
for(int i=m-start-2;i>start&&n-start-1>start;i--)
{
res.push_back(matrix[i][start]);
time++;
}
start++;
}
return res;
}
};

Updated version, imagine you go from (0,0) and change direction every time you meet a wall or some element that is visited.

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int m=matrix.size();
if(m==0)
return res;
int n=matrix[0].size();
vector<vector<bool> > visited(m,vector<bool>(n,0));
int i=0,j=0;
int dir=0;
int count=0;
while(1)
{
res.push_back(matrix[i][j]);
visited[i][j]=1;
count++;
if(count==m*n)
break;
if(dir==0)
{
if(j!=n-1&&visited[i][j+1]==0)
j++;
else
{
dir++;
i++;
}
}
else if(dir==1)
{
if(i!=m-1&&visited[i+1][j]==0)
i++;
else
{
dir++;
j--;
}
}
else if(dir==2)
{
if(j!=0&&visited[i][j-1]==0)
j--;
else
{
dir++;
i--;
}
}
else if(dir==3)
{
if(i!=0&&visited[i-1][j]==0)
i--;
else
{
dir=0;
j++;
}
}
}
return res;
}
};



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: