C_棋盘覆盖

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C_棋盘覆盖相关的知识,希望对你有一定的参考价值。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include<memory.h>
 4 
 5 int nCount = 0;
 6 int Matrix[100][100];
 7 
 8 void chessBoard(int tr, int tc, int dr, int dc, int size);
 9 
10 int main()
11 {
12     int size,r,c,row,col;
13     memset(Matrix,0,sizeof(Matrix));
14     printf("输入棋盘的大小(大小必须是2的n次幂):");
15     scanf("%d",&size);
16     printf("请输入特殊方格的坐标:");
17     scanf("%d%d",&row,&col);
18     chessBoard(0,0,row,col,size);
19 
20     printf("\\n");
21     for (r = 0; r < size; r++)
22     {
23         for (c = 0; c < size; c++)
24         {
25             printf("%3d ",Matrix[r][c]);
26         }
27         printf("\\n");
28     }
29 
30     return 0;
31 }
32 
33 void chessBoard(int tr, int tc, int dr, int dc, int size)
34 {
35     //tr and tc represent the top left corner‘s coordinate of the matrix
36     int s,t;
37     if (1 == size) return;
38 
39     s = size/2; //The number of grid the matrix‘s edge
40     t = ++ nCount;
41 
42     //locate the special  grid on bottom right corner
43     if (dr < tr + s && dc < tc +s)
44     {
45         chessBoard(tr,tc,dr,dc,s);
46     }
47     else
48     {
49         Matrix[tr+s-1][tc+s-1] = t;
50         chessBoard(tr,tc,tr+s-1,tc+s-1,s);
51     }
52 
53     //locate the special  grid on bottom left corner
54     if (dr < tr + s && dc >= tc + s )
55     {
56         chessBoard(tr,tc+s,dr,dc,s);
57     }
58     else
59     {
60         Matrix[tr+s-1][tc+s] = t;
61         chessBoard(tr,tc+s,tr+s-1,tc+s,s);
62     }
63 
64     //locate the special  grid on top right corner
65     if (dr >= tr + s && dc < tc + s)
66     {
67         chessBoard(tr+s,tc,dr,dc,s);
68     } 
69     else
70     {
71         Matrix[tr+s][tc+s-1] = t;
72         chessBoard(tr+s,tc,tr+s,tc+s-1,s);
73     }
74 
75     //locate the special  grid on top left corner
76     if (dr >= tr + s && dc >= tc + s)
77     {
78         chessBoard(tr+s,tc+s,dr,dc,s);
79     } 
80     else
81     {
82         Matrix[tr+s][tc+s] = t;
83         chessBoard(tr+s,tc+s,tr+s,tc+s,s);
84     }
85 
86 }

 技术分享

 

以上是关于C_棋盘覆盖的主要内容,如果未能解决你的问题,请参考以下文章

棋盘覆盖问题——分治法——代码清晰易懂

算法复习_分治算法之二分搜索棋盘覆盖快速排序

棋盘覆盖问题与可视化代码演示

用python代码编写象棋界面,棋盘覆盖问题

NYOJ 棋盘覆盖

「CH6801」棋盘覆盖