顺时针打印矩阵




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

我首先打印行 1、2、3   然后打印列  6
再打印行       9、8、7   再打印列     4
我们要注意的是什么情况下才会打印,也就是说如:
    
因些要对要打印的条件进行严格限制。
左图中,由于有只有两行,那么左边那列就没有了。
中间那图,由于只有一列,那么第二次的行和列就没了。
右边的图只有一列,那么就只能第一次打印行了。
因此我们需对剩下的行数和列数进行计数判断:
    如果行数和列数都大于2,那么第一次的行,列,第二次的行列都打。
    如果只有两行多列,那么不打列。
    如果只有一行多列,那么只打行。
    。。。。。。。。
  

  1. #ifndef TIME_WISE_PRINT_MATRIX_H
  2. #define TIME_WISE_PRINT_MATRIX_H
  3. #include<iostream>
  4. #define COLUS 3
  5. void printMatrixCore(int (*)[COLUS],int rows,int);
  6. void timewisePrintMatrix(int (*matrix)[COLUS],int rows){
  7. if(matrix==NULL){
  8. return;
  9. }
  10. int printCount=0;
  11. while(2*printCount<COLUS&&2*printCount<rows){
  12. printMatrixCore(matrix,rows,printCount);
  13. printCount++;
  14. }
  15. }
  16. void printMatrixCore(int (*matrix)[COLUS],int rows,int count){
  17. int rowStart=count;
  18. int rowEnd=rows-count-1;
  19. int colStart=count;
  20. int colEnd=COLUS-count-1;
  21. //print the first rows
  22. for(int i=colStart; i<=colEnd; i++){
  23. std::cout<<matrix[rowStart][i]<<",";
  24. }
  25. //print the second column
  26. if(rowEnd-rowStart>1){
  27. for(int i=rowStart+1; i<=rowEnd-1; i++){
  28. std::cout<<matrix[i][colEnd]<<",";
  29. }
  30. }
  31. //print the second row
  32. if(rowEnd-rowStart>=1){
  33. for(int i=colEnd; i>=colStart; i--){
  34. std::cout<<matrix[rowEnd][i]<<",";
  35. }
  36. }
  37. //print the first col
  38. if(rowEnd-rowStart>1&&colEnd-colStart>=1){
  39. for(int i=rowEnd-1; i>=rowStart+1; i--){
  40. std::cout<<matrix[i][colStart]<<",";
  41. }
  42. }
  43. }
  44. #endif

测试:
    
  1. #include"timeWisePrintMatrix.h"
  2. #include<iostream>
  3. int main(){
  4. int matrix[3][3]={{1,2,3},{4,5,6},{7,8,9}};
  5. timewisePrintMatrix(matrix,3);
  6. }
输出:
    






原文地址:https://www.cnblogs.com/yml435/p/4673983.html