[LeetCode]54. 螺旋矩阵+59. 螺旋矩阵 II

按右、下、左、上的方向顺序遍历矩阵,某方向无法继续有效访问时变换方向。
54. 螺旋矩阵
相似题:59. 螺旋矩阵 II

//54.螺旋矩阵代码
class Solution {
public:
    //按右,下,左,上的顺序访问矩阵
    const int movex[4]={0,1,0,-1};
    const int movey[4]={1,0,-1,0};
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m=matrix.size();
        int n;
        if (m>0) n=matrix[0].size();
        vector <int> ans;
        ans.clear();
        if (m==0) return ans;
        int now=0;
        int nowx=0;
        int nowy=0;
        int cnt=0;
        bool used[m+5][n+5];
        ans.push_back(matrix[0][0]);
        memset(used,false,sizeof(used));
        used[0][0]=true;
        while (cnt<m*n-1){
            cnt++;
            if (nowx+movex[now]<0 || nowx+movex[now]>=m || nowy+movey[now]<0 || nowy+movey[now]>=n){
                //变换方向
                now++;
                now%=4;
            }
            else if (used[nowx+movex[now]][nowy+movey[now]]){
                //变换方向
                now++;
                now%=4;
            }
            used[nowx+movex[now]][nowy+movey[now]]=true;
            nowx+=movex[now];
            nowy+=movey[now];
            ans.push_back(matrix[nowx][nowy]);
        }
        return ans;
    }
};
//59. 螺旋矩阵 II代码
class Solution {
public:
    const int movex[4]={0,1,0,-1};
    const int movey[4]={1,0,-1,0};
    vector<vector<int>> generateMatrix(int n) {
        int nowx=0;
        int nowy=0;
        int now=0;
        int cnt=0;
        int used[n+5][n+5];
        for (int i=0;i<n;i++){
            for (int j=0;j<n;j++){
                used[i][j]=0;
            }
        }
        cnt++;
        used[0][0]=cnt;
        while (cnt<n*n){
            cnt++;
            if (nowx+movex[now]<0 || nowx+movex[now]>=n || nowy+movey[now]<0 || nowy+movey[now]>=n){
                //变换方向
                now++;
                now%=4;
            }
            else if (used[nowx+movex[now]][nowy+movey[now]]>0){
                //变换方向
                now++;
                now%=4;
            }
            nowx+=movex[now];
            nowy+=movey[now];
            used[nowx][nowy]=cnt;
        }
        vector<vector<int>> ans;
        for (int i=0;i<n;i++){
            vector<int> help;
            help.clear();
            for (int j=0;j<n;j++) help.push_back(used[i][j]);
            ans.push_back(help);
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值