其他 顺时针打印矩阵 STL

题目描述

对于一个矩阵,请设计一个算法从左上角(mat0)开始,顺时针打印矩阵元素。

给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。

测试样例:

[[1,2],[3,4]],2,2
返回:[1,2,4,3]
class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
        // write code here
        int a,b,c,d;
          a=0,b=n-1;
        c=0,d=m-1;
        vector<int> ves;
        while(1)
        {
            if(a>b || c>d)
            {
                break;
            }
            for(int i=c;i<=d;++i)
            {
                ves.push_back(mat[a][i]);
            }
            a++;
            if(a==n || a>b) break;
            for(int i=a;i<=b;++i)
            {
                ves.push_back(mat[i][d]);
            }
            d--;
            if(d==-1 || d<c) break;
            for(int i=d;i>=c;--i)
            {
                ves.push_back(mat[b][i]);
            }
            b--;
            if(b==-1 || a>b) break;
            for(int i=b;i>=a;--i)
            {
                ves.push_back(mat[i][c]);
            }
            c++;
            if(c==m || d<c) break;
        }     
        return ves; 
    }
};
Last modification:January 11th, 2020 at 10:50 pm
如果觉得我的文章对你有用,请随意赞赏