nowcoder-顺时针打印矩阵-模拟魔方逆时针旋转
生活随笔
收集整理的這篇文章主要介紹了
nowcoder-顺时针打印矩阵-模拟魔方逆时针旋转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
順時針打印矩陣
輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
矩陣為:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16思想
首先將第一行打印,并刪除第一行
5 6 7 8 9 10 11 12 13 14 15 16將矩陣逆時針旋轉
8 12 16 7 11 15 6 10 14 5 9 13將第一行打印,刪除第一行
….
重復上述步驟,直到剩余矩陣為空。
代碼
class Solution { public:vector<int> printMatrix(vector<vector<int> > matrix) {while(!matrix.empty()){ //判斷剩余矩陣是否為空for(int i = 0; i < matrix[0].size(); i++){ans.push_back(matrix[0][i]); //輸出第一行}matrix.erase(matrix.begin()); //刪除第一行temp = Contrarotate(matrix); //逆時針旋轉矩陣matrix.clear();matrix = temp;}return ans;}vector<vector<int> > Contrarotate(vector<vector<int> > matrix){vector<vector<int> > vec; if(matrix.empty())return vec;int m = matrix.size(), n = matrix[0].size();vec.resize(n); //初始化旋轉后的矩陣的大小for(int c = 0; c < vec.size(); c++){vec[c].resize(m);}for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){vec[i][j] = matrix[j][n-1-i]; //逆時針旋轉}}return vec;} private: vector<vector<int> > temp; vector<int> ans; };總結
以上是生活随笔為你收集整理的nowcoder-顺时针打印矩阵-模拟魔方逆时针旋转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Anaconda的Spyder闪退的我的
- 下一篇: (附源码)spring boot中小学餐