环形矩阵

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 }

 

 

 

 

 

 

转载于:https://www.cnblogs.com/zhouwenJS/p/3837852.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值