顺时针打印矩阵


打印方法:
我们采用计数的方式进行打印,如第一次打印,第二次打印,第。。。。。。。
我们知道,第一次打印时,是打印其最”外围“数字。

我首先打印行 1、2、3 然后打印列 6
再打印行 9、8、7 再打印列 4
我们要注意的是什么情况下才会打印,也就是说如:

因些要对要打印的条件进行严格限制。
左图中,由于有只有两行,那么左边那列就没有了。
中间那图,由于只有一列,那么第二次的行和列就没了。
右边的图只有一列,那么就只能第一次打印行了。
因此我们需对剩下的行数和列数进行计数判断:
如果行数和列数都大于2,那么第一次的行,列,第二次的行列都打。
如果只有两行多列,那么不打列。
如果只有一行多列,那么只打行。
。。。。。。。。
#ifndef TIME_WISE_PRINT_MATRIX_H#define TIME_WISE_PRINT_MATRIX_H#include<iostream>#define COLUS 3void printMatrixCore(int (*)[COLUS],int rows,int);void timewisePrintMatrix(int (*matrix)[COLUS],int rows){if(matrix==NULL){return;}int printCount=0;while(2*printCount<COLUS&&2*printCount<rows){printMatrixCore(matrix,rows,printCount);printCount++;}}void printMatrixCore(int (*matrix)[COLUS],int rows,int count){int rowStart=count;int rowEnd=rows-count-1;int colStart=count;int colEnd=COLUS-count-1;//print the first rowsfor(int i=colStart; i<=colEnd; i++){std::cout<<matrix[rowStart][i]<<",";}//print the second columnif(rowEnd-rowStart>1){for(int i=rowStart+1; i<=rowEnd-1; i++){std::cout<<matrix[i][colEnd]<<",";}}//print the second rowif(rowEnd-rowStart>=1){for(int i=colEnd; i>=colStart; i--){std::cout<<matrix[rowEnd][i]<<",";}}//print the first colif(rowEnd-rowStart>1&&colEnd-colStart>=1){for(int i=rowEnd-1; i>=rowStart+1; i--){std::cout<<matrix[i][colStart]<<",";}}}#endif
测试:
#include"timeWisePrintMatrix.h"#include<iostream>int main(){int matrix[3][3]={{1,2,3},{4,5,6},{7,8,9}};timewisePrintMatrix(matrix,3);}
输出:

浙公网安备 33010602011771号