题解 | #顺时针打印矩阵#

顺时针打印矩阵

http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
思路:
1.输出第一行: ans=[1,2,3,4]
2.然后把剩下的矩阵逆时针旋转90度:
[8,12,16]
[7,11,15]
[6,10,14]
[5,9,13]
3.重复以上操作:ans=[1,2,3,4,8,12,16]
[15,14,13]
[11,10,9]
[7,6,5]
4.直到矩阵为空

c++代码:


class Solution {
public:
    vector<vector<int> > rotate(vector<vector<int> > matrix){
        int m = matrix.size();
        int n = matrix[0].size();
        if(m<=1&&n<=1) return matrix;
        vector<vector<int> > ans(n);
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                ans[j].push_back(matrix[i][n-j-1]);
            }
        }
        return ans;
    }

    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> ans;
        int s=1;

        while(s){
            int m = matrix.size();
            int n = matrix[0].size();
            vector<vector<int> > temp(m-1);
            for(int j=0;j<n;j++){
                ans.push_back(matrix[0][j]);
               for(int i=0;i<m-1;i++){

                   temp[i].push_back(matrix[i+1][j]);

               }
            }
            if(temp.size()) matrix = rotate(temp);
            else matrix={};
            s = matrix.size();  
        }
        return ans;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务