//输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, //例如,如果输入如下矩阵: 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> using namespace std; void Grial(int (*a)[5],int n) { int a1 = 0; int b1 = n-1; bool visted[n][n]; for(int k=0;k<n;k++) { for(int m=0;m<n;m++) { visted[k][m]=false; } } int i=0; int j=0; while(1) { for(i=a1;i<=b1;i++) { if(visted[a1][i]==false) { cout<<a[a1][i]<<" " ; visted[a1][i]=true; } } for(j=a1+1;j<=b1;j++) { if(visted[j][b1]==false) { cout<<a[j][b1]<<" "; visted[j][b1]=true; } } for(i=b1-1;i>=a1;i--) { if(visted[b1][i]==false) { cout<<a[b1][i]<<" " ; visted[b1][i]=true; } } for(i=b1-1;i>a1;i--) { if(visted[i][a1]==false) { cout<<a[i][a1]<<" "; visted[i][a1]=true; } } i++; if(visted[i][a1]==true && visted[i+1][a1]==true && visted[i][a1+1]==true && visted[i][a1-1]==true && visted[i-1][a1]==true)return ; a1++; b1--; } } int main() { int a[][5]={1,2,3,4,5, 6,7,8,9,10, 11,12,13,14,15 ,16,17,18,19,20 ,21,22,23,24,25}; Grial(a,5); return 0; }
结果如下:
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13
时间: 2024-10-03 22:29:03