leetcode 53: Spiral Matrix

来源:互联网 发布:2017淘宝销量排行榜 编辑:程序博客网 时间:2024/05/21 06:41
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;    }};


                                             
0 0
原创粉丝点击