码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer 顺时针打印矩阵

时间:2017-09-03 00:22:24      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:https   scribe   span   circle   tor   void   matrix   coding   target   

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
思路:一定要记住循环继续的条件是columns > start * 2,rows > start * 2;
一圈的打印分为四步:
第一步:无条件打印第一行,从左往右;
第二步:终止行号大于起始行号,打印最后一列,从上往下;
第三步:至少有两行两列才能进行打印,要求起始行号小于终止行号,起始列号小于终止列号,从左往右打印。
第四步:至少需要三行两列才能进行打印,终止行号比起始行号至少大2,终止列号大于起始列号。
 
分为两个函数,一个函数实现打印一圈的功能,另一个函数实现主循环。
 1 class Solution {
 2 public:
 3     void printfCircle(vector<vector<int> > matrix,vector<int>& result,int start,int rows,int columns){
 4         int endRows = rows - start - 1;
 5         int endColumns = columns - start - 1;
 6         //打印第一行
 7         for(int i = start;i <= endColumns;++i){
 8             result.push_back(matrix[start][i]);
 9         }
10         //打印最后一列
11         if(start < endRows){
12             for(int i = start + 1;i <= endRows;++i){
13                 result.push_back(matrix[i][endColumns]);
14             }
15         }
16         //打印最后一行
17         if(start < endRows && start < endColumns){
18             for(int i = endColumns - 1;i >= start;--i){
19                 result.push_back(matrix[endRows][i]);
20             }
21         }
22         //打印第一列
23         if(start < endRows - 1 && start < endColumns){
24             for(int i = endRows - 1;i >= start + 1;--i){
25                 result.push_back(matrix[i][start]);
26             }
27         }
28     }
29     vector<int> printMatrix(vector<vector<int> > matrix) {
30         vector<int> result;
31         if(matrix.empty()){
32             return {};
33         }
34         if(matrix[0].empty()){
35             return {};
36         }
37         int start = 0;
38         int rows = matrix.size(),columns = matrix[0].size();
39         while(rows > 2*start && columns > 2*start){
40             printfCircle(matrix,result,start,rows,columns);
41             ++start;
42         }
43         return result;
44     }
45 };

 

 
 

剑指offer 顺时针打印矩阵

标签:https   scribe   span   circle   tor   void   matrix   coding   target   

原文地址:http://www.cnblogs.com/dingxiaoqiang/p/7468309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!