#include <iostream>
#include <iomanip>
constexpr size_t max = 16;
size_t board[max][max] = {0};
int tile = 1;
int size = max;
void chess_board(int tr, int tc, int dr, int dc, size_t size)
{
if (size == 1)
{
return;
}
int t = tile++;
int s = size / 2;
// 左上
if (dr < tr + s && dc < tc + s)
{
chess_board(tr, tc, dr, dc, s);
}
else
{
board[tr + s - 1][tc + s - 1] = t;
chess_board(tr, tc, tr + s - 1, tc + s - 1, s);
}
// 右上
if (dr < tr + s && dc >= tc + s)
{
chess_board(tr, tc + s, dr, dc, s);
}
else
{
board[tr + s - 1][tc + s] = t;
chess_board(tr, tc + s, tr + s - 1, tc + s, s);
}
// 左下
if (dr >= tr + s && dc < tc + s)
{
chess_board(tr + s, tc, dr, dc, s);
}
else
{
board[tr + s][tc + s - 1] = t;
chess_board(tr + s, tc, tr + s, tc + s - 1, s);
}
// 右下
if (dr >= tr + s && dc >= tc + s)
{
chess_board(tr + s, tc + s, dr, dc, s);
}
else
{
board[tr + s][tc + s] = t;
chess_board(tr + s, tc + s, tr + s, tc + s, s);
}
}
void print_board()
{
for (size_t i = 0; i < max; i++)
{
for (size_t j = 0; j < max; j++)
{
std::cout << std::setw(5) << board[i][j];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main()
{
print_board();
chess_board(0, 0, 9, 7, max);
print_board();
}
package main
import "fmt"
var max = 16
var tile = 1
var board [16][16]int
func chessBoard(tr, tc, dr, dc, size int) {
if size == 1 {
return
}
t := tile
tile++
s := size / 2
if dr < tr+s && dc < tc+s {
chessBoard(tr, tc, dr, dc, s)
} else {
board[tr+s-1][tc+s-1] = t
chessBoard(tr, tc, tr+s-1, tc+s-1, s)
}
if dr < tr+s && dc >= tc+s {
chessBoard(tr, tc+s, dr, dc, s)
} else {
board[tr+s-1][tc+s] = t
chessBoard(tr, tc+s, tr+s-1, tc+s, s)
}
if dr >= tr+s && dc < tc+s {
chessBoard(tr+s, tc, dr, dc, s)
} else {
board[tr+s][tc+s-1] = t
chessBoard(tr+s, tc, tr+s, tc+s-1, s)
}
if dr >= tr+s && dc >= tc+s {
chessBoard(tr+s, tc+s, dr, dc, s)
} else {
board[tr+s][tc+s] = t
chessBoard(tr+s, tc+s, tr+s, tc+s, s)
}
}
func printBoard() {
for i := 0; i < max; i++ {
for j := 0; j < max; j++ {
fmt.Print(board[i][j], "\t")
}
fmt.Println()
}
fmt.Println()
}
func main() {
printBoard()
chessBoard(0, 0, 9, 7, max)
printBoard()
}
结果
棋盘覆盖问题运行结果
网友评论