剑指offer-面试题29-顺时针打印矩阵-矩阵

/*
题目:
	输入一个矩阵,按照从外到内顺时针的顺序依次打印每一个数字。
*/
/*
思路:
	1、将打印矩阵看作是打印一个个从外向内的环。
	2、每一个环都有一个起始节点,起始节点的坐标*2小于行数和列数。
	3、对于每一个环,分别打印从左到右,从上到下,从右到左,从下到上的数字。
*/
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stdio.h>
#include<vector>

using namespace std;
//res传引用
void printMatrixs(vector<vector<int> > mat,int rows,int columns,int start,vector<int> &res){
    int right = columns - start;
    int down = rows -start;

    //从左到右打印一行
    for(int i = start; i < right; i++){
        res.push_back(mat[start][i]);
    }
    //从上到下打印一列
    for(int i = start + 1; i < down; i++){
        res.push_back(mat[i][right-1]);
    }
    //从右到左打印一行,不和从右到左打印的行重复
    if(down - 1 != start){
         for(int i = right - 2; i >= start; i--){
            res.push_back(mat[down-1][i]);
        }
    }

    //从下到上打印一列,不和从上到下打印的列重复
    if(start != right - 1){
        for(int i = down - 2; i > start; i--){
            res.push_back(mat[i][start]);
        }
    }

}

vector<int> clockwisePrint(vector<vector<int>> mat, int rows, int columns) {
    if(rows == 0 || columns == 0) throw("invalid parameters");
    int start = 0;
    vector<int> res;
    while(start*2 < rows && start*2 <columns){
        printMatrixs(mat,rows,columns,start,res);
        start++;
    }
    return res;
}



int main(){
   vector<vector<int>> mat = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
   vector<int> res = clockwisePrint(mat,4,4);
   for(int i = 0; i < res.size(); i++){
    cout<<res[i]<<" ";
   }
}

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11930519.html
今日推荐