1. 程式人生 > >劍指offer之【順時針打印矩陣】

劍指offer之【順時針打印矩陣】

如果 div code clas logs ice 順時針打印 順時針打印矩陣 個數

題目:

  順時針打印矩陣

鏈接:

  https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述:

  輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 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,打印環;

代碼:

  

 1 class Solution{
 2 public:
 3     vector<int> printMatrix(vector<vector<int>> matrix){
 4         int row = matrix.size();        // 行數
 5         int col = matrix[0].size();        // 列數
 6         int
rl = 0,rh = row-1,cl = 0,ch = col-1; 7 vector<int> res; 8 while(rl <= rh && cl <= ch){ // 判斷是否進行打印 9 printOut(matrix, res , rl, rh, cl ,ch); 10 ++rl; 11 --rh; 12 ++cl; 13 --ch; 14 } 15 return
res; 16 } 17 void printOut(vector<vector<int>> &matrix,vector<int> &res, int rl,int rh,int cl,int ch){ 18 if(rl == rh && cl == ch) //判斷是否只需要打印點 19 res.push_back(matrix[rl][cl]); 20 else if(rl == rh ){ //判斷是否只需要打印列 21 for(int i =cl; i<= ch; ++i){ 22 res.push_back(matrix[rl][i]); 23 } 24 } 25 else if(cl == ch){ //判斷是否只需要打印行 26 for(int i = rl; i <= rh ;++i){ 27 res.push_back(matrix[i][cl]); 28 } 29 } 30 else{ //打印矩陣環 31 for(int i = cl; i<= ch;++i){ 32 res.push_back(matrix[rl][i]); 33 } 34 for(int i = rl+1; i <= rh-1 ; ++i){ 35 res.push_back(matrix[i][ch]); 36 } 37 for(int i = ch ;i >= cl; --i){ 38 res.push_back(matrix[rh][i]); 39 } 40 for(int i = rh-1 ; i>= rl+1; --i){ 41 res.push_back(matrix[i][cl]); 42 } 43 } 44 } 45 };

劍指offer之【順時針打印矩陣】