<剑指Offer>面试题29: 顺时针打印矩阵

题目描述 牛客网

  • 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
  • 例如,如果输入如下矩阵
 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

题目解读

  • 剑指Offer 161

代码

#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:

    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> temp;
        int row = 0;
        int col = 0;
        int rows = matrix.size() - 1;
        int cols = matrix[0].size() -1;

        while(row <= rows && col <= cols){
            // 向右
            if(row <= rows && col <= cols){
                for(int j = col; j <= cols; j ++){
                    temp.push_back(matrix[row][j]);
                }
                row ++;
            }
            
            // 向下
            if(row <= rows && col <= cols){
                for(int i = row; i <= rows; i ++){
                    temp.push_back(matrix[i][cols]);
                }
                cols --;
            }
                   
            // 向左
            if(row <= rows && col <= cols){
                for(int j = cols; j >= col; j --){
                    temp.push_back(matrix[rows][j]);
                }
                rows --;
            }
            
            // 向上
            if(row <= rows && col <= cols){
                for(int i = rows; i >= row; i --){
                    temp.push_back(matrix[i][col]);
                }
                col ++;
            }

        }
        return temp;
    }

    void create(vector<vector<int> > &matrix){
        vector<int> a;

        for(int i = 1; i <= 16; i ++){
            a.push_back(i);

            if(i%4 == 0){
                matrix.push_back(a);
                a.clear();
            }
        }

        for(int i=0; i < matrix.size(); i++){
            for(int j=0; j < matrix[0].size(); j++){
                cout<<matrix[i][j]<<" ";
            }
            cout<<endl;
        }
    }   
};

main(){
    
    vector<vector<int> > matrix;

    Solution ss;
    ss.create(matrix);
    vector<int> tt = ss.printMatrix(matrix);
    for(int i=0; i < tt.size(); i++){
        cout<<tt[i]<<" ";
    }
    cout<<endl;
}

总结展望

  • 不涉及数据结构和算法,仅仅是考验编程基本功,本题相当到位
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容