首页 > 代码库 > 环形矩阵

环形矩阵

1.逆时针

代码:

 1 // huanxingjz.cpp : Defines the entry point for the console application. 2 // 3  4 #include "stdafx.h" 5 #include <stdio.h> 6 #include <iostream> 7 #include "windows.h" 8 #define MAX 40 9 using namespace std;10 int n,square[MAX][MAX];11 12 int ok(int x,int y)13 {14     return (0<=x&&x<n&&0<=y&&y<n&&square[x][y]==0);15 }16 17 int main()18 {19     int i,j,k,d;20     printf("请输入螺旋方阵的阶数n:");21     //scanf("%d",&n);22     cin>> n;23     memset(square,0,MAX*MAX*sizeof(int));24 25     for(i=j=d=0,k=1;k<=n*n;++k)26     {27         square[i][j]=k;28         switch(d%4)29         {30         case 0:if(ok(i+1,j)) ++i;31                else ++d,++j;32                break;33         case 1:if(ok(i,j+1)) ++j;34                else ++d,--i;35                break;36         case 2:if(ok(i-1,j)) --i;37                else ++d,--j;38                break;39         case 3:if(ok(i,j-1)) --j;40                else ++d,++i;41                42         43         }44     }45 46     for(i=0;i<n;++i)47     {48         printf("\n");49         for(j=0;j<n;++j)50             printf("%4d",square[i][j]);51         printf("\n");        52     }53     printf("\n"); 54     Sleep(10000);55     /*system("pause");*/56 }

2.顺时针

代码

 1 // huanxingjz.cpp : Defines the entry point for the console application. 2 // 3  4 #include "stdafx.h" 5 #include <stdio.h> 6 #include <iostream> 7 #include "windows.h" 8 #define MAX 40 9 using namespace std;10 int n,square[MAX][MAX];11 12 int ok(int x,int y)13 {14     return (0<=x&&x<n&&0<=y&&y<n&&square[x][y]==0);15 }16 17 int main()18 {19     int i,j,k,d;20     printf("请输入螺旋方阵的阶数n:");21     //scanf("%d",&n);22     cin>> n;23     memset(square,0,MAX*MAX*sizeof(int));24 25     for(i=j=d=0,k=1;k<=n*n;++k)26     {27         square[i][j]=k;28         switch(d%4)29         {30         case 0:if(ok(i,j+1)) ++j;31                else ++d,++i;32                break;33         case 1:if(ok(i+1,j)) ++i;34                else ++d,--j;35                break;36         case 2:if(ok(i,j-1)) --j;37                else ++d,--i;38                break;39         case 3:if(ok(i-1,j)) --i;40                else ++d,++j;41        42         43         }44     }45 46     for(i=0;i<n;++i)47     {48         printf("\n");49         for(j=0;j<n;++j)50             printf("%4d",square[i][j]);51         printf("\n");        52     }53     printf("\n"); 54     Sleep(10000);55     /*system("pause");*/56 }