题目描述

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

给定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
        vector<int> ans;
        if(n<1)
            return ans;
        int left = 0, top = 0, right = m-1, bot = n-1;
        while(left<=right&&top<=bot)
        {
            if(left == right)  // one col
            {
                for(int i = top;i<=bot;i++)
                    ans.push_back(mat[i][left]);
            }
            else
            {
                if(top == bot)
                {
                    for(int i = left;i<=right;i++)
                        ans.push_back(mat[top][i]);
                }
                else
                {
                    for(int i = left;i<right;i++)
                        ans.push_back(mat[top][i]);
                    for(int i = top;i<bot;i++)
                        ans.push_back(mat[i][right]);
                    for(int i = right;i>left;i--)
                        ans.push_back(mat[bot][i]);
                    for(int i = bot;i>top;i--)
                        ans.push_back(mat[i][left]);
                }
            }      
            left++,top++;
            right--,bot--;
        }
        return ans;
    }
};

 

相关文章:

猜你喜欢
  • 2022-12-23
相关资源
相似解决方案