题目: 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 例如: 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 代码
#include<iostream> #include<cstdlib> using namespace std; void PrintMatrixInCricle(int arr[],int cols,int rows,int start) { int endX=cols-1-start; int endY=rows-1-start; for(int i=start;i<=endX;i++)//从左到右打印一行 { int num=arr[start*rows+i]; cout<<num<<" "; } if (start<endY)//从上到下打印一列 { for(int i=start+1;i<=endY;i++) { int num=arr[i*rows+endX]; cout<<num<<" "; } } if(start<endX&&start<endY) { for(int i=endX-1;i>=start;i--) { int num=arr[endY*rows+i]; cout<<num<<" "; } } if(start<endX&&start<endY-1) { for(int i=endY-1;i>=start+1;i--) { int num=arr[i*rows+start]; cout<<num<<" "; } } cout<<endl; } void PrintMatrix(int arr[],int cols,int rows) { if (arr==NULL||cols<=0||rows<=0) return; int start=0; while (cols>start*2&&rows>start*2) { PrintMatrixInCricle(arr,cols,rows,start); ++start; } } void test() { int arr[]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; PrintMatrix(arr,4,4); } #include "Matrix.h" int main() { test(); system("pause"); return 0; }结果