C语言编写残缺棋盘问题代码
时间: 2024-02-25 11:29:07 浏览: 90
C语言编写棋盘问题
4星 · 用户满意度95%
以下是一个解决残缺棋盘问题的C语言代码:
```c
#include<stdio.h>
#include<math.h>
#define MAXN 1024
int tile = 1; // 全局变量,记录铺的方块数
int board[MAXN][MAXN]; // 棋盘
int special_row, special_col; // 特殊方格的行和列
// 把棋盘分成四个象限
void divide(int tr, int tc, int dr, int dc, int size) {
if(size == 1) return; // 边界条件
int t_mid_r = (tr + dr) / 2; // 计算上半部分棋盘中心的行
int t_mid_c = (tc + dc) / 2; // 计算上半部分棋盘中心的列
int d_mid_r = t_mid_r + 1; // 计算下半部分棋盘中心的行
int d_mid_c = t_mid_c + 1; // 计算下半部分棋盘中心的列
// 对左上象限进行递归
if(special_row <= t_mid_r && special_col <= t_mid_c) {
board[d_mid_r][d_mid_c] = board[t_mid_r][t_mid_c] = tile++;
board[d_mid_r][t_mid_c+1] = board[t_mid_r+1][t_mid_c] = tile++;
divide(tr, tc, t_mid_r, t_mid_c, size/2);
}
else {
board[t_mid_r][t_mid_c] = tile++;
board[d_mid_r][t_mid_c] = tile++;
board[t_mid_r][d_mid_c] = tile++;
board[d_mid_r][d_mid_c] = tile++;
divide(tr, tc, t_mid_r, t_mid_c, size/2);
}
// 对右上象限进行递归
if(special_row <= t_mid_r && special_col > t_mid_c) {
board[d_mid_r][t_mid_c] = board[t_mid_r][d_mid_c] = tile++;
board[d_mid_r][d_mid_c] = board[t_mid_r+1][t_mid_c+1] = tile++;
divide(tr, t_mid_c+1, t_mid_r, dc, size/2);
}
else {
board[t_mid_r][d_mid_c] = tile++;
board[d_mid_r][d_mid_c] = tile++;
board[t_mid_r+1][t_mid_c+1] = tile++;
board[d_mid_r][t_mid_c] = tile++;
divide(tr, t_mid_c+1, t_mid_r, dc, size/2);
}
// 对左下象限进行递归
if(special_row > t_mid_r && special_col <= t_mid_c) {
board[t_mid_r][d_mid_c] = board[d_mid_r][t_mid_c] = tile++;
board[t_mid_r+1][t_mid_c+1] = board[d_mid_r][d_mid_c] = tile++;
divide(t_mid_r+1, tc, dr, t_mid_c, size/2);
}
else {
board[t_mid_r][d_mid_c] = tile++;
board[d_mid_r][t_mid_c] = tile++;
board[t_mid_r+1][t_mid_c+1] = tile++;
board[d_mid_r][d_mid_c] = tile++;
divide(t_mid_r+1, tc, dr, t_mid_c, size/2);
}
// 对右下象限进行递归
if(special_row > t_mid_r && special_col > t_mid_c) {
board[t_mid_r][d_mid_c] = board[d_mid_r][t_mid_c] = tile++;
board[t_mid_r+1][t_mid_c] = board[d_mid_r][d_mid_c] = tile++;
divide(t_mid_r+1, t_mid_c+1, dr, dc, size/2);
}
else {
board[t_mid_r][d_mid_c] = tile++;
board[d_mid_r][t_mid_c] = tile++;
board[t_mid_r+1][t_mid_c] = tile++;
board[d_mid_r][d_mid_c] = tile++;
divide(t_mid_r+1, t_mid_c+1, dr, dc, size/2);
}
}
int main() {
int k, i, j;
scanf("%d%d%d", &k, &special_row, &special_col);
// 计算棋盘大小
int size = pow(2, k);
// 把特殊方格填上,从1开始填充
board[special_row][special_col] = 0;
// 对棋盘进行递归铺砖
divide(0, 0, size-1, size-1, size);
// 输出棋盘
for(i = 0; i < size; i++) {
for(j = 0; j < size; j++) {
printf("%-3d", board[i][j]);
}
printf("\n");
}
return 0;
}
```
该代码中使用了分治算法,把棋盘分成四个象限,然后对每个象限进行递归铺砖。在铺砖的过程中,根据特殊方格所在的象限,分别对四个象限进行递归处理。最后输出棋盘即可。
阅读全文