棋盤覆蓋

潘仁波發表於2021-01-02

在這裡插入圖片描述

#include <iostream>

using namespace std;

int tile = 0;
int board[33][33] = {{0}, {0}};

int MatrixSize(int k)
{
    int size = 1;

    for (int i = 0; i < k; i++)
    {
        size *= 2;
    }

    return size;
}

void ChessBoard(int tr, int tc, int dr, int dc, int size)
{
    if (size == 1)
    {
        return;
    }
    int t = tile++, s = size / 2;

    // left top
    if (dr < tr + s && dc < tc + s)
    {
        ChessBoard(tr, tc, dr, dc, s);
    }
    else
    {
        board[tr + s - 1][tc + s - 1] = tile; // right down filled one
        ChessBoard(tr, tc, tr + s - 1, tc + s - 1, s);
    }

    // right top
    if (dr < tr + s && dc >= tc + s)
    {
        ChessBoard(tr, tc + s, dr, dc, s);
    }
    else
    {
        board[tr + s - 1][tc + s] = tile; // left down one
        ChessBoard(tr, tc + s, tr + s - 1, tc + s, s);
    }

    // left down
    if (dr >= tr + s && dc < tc + s)
    {
        ChessBoard(tr + s, tc, dr, dc, s);
    }
    else
    {
        board[tr + s][tc + s - 1] = tile; // right up one
        ChessBoard(tr + s, tc, tr + s, tc + s - 1, s);
    }

    // right down
    if (dr >= tr + s && dc >= tc + s)
    {
        ChessBoard(tr + s, tc + s, dr, dc, s);
    }
    else
    {
        board[tr + s][tc + s] = tile; // left up one
        ChessBoard(tr + s, tc + s, tr + s, tc + s, s);
    }
}

int main()
{
    int k, dr, dc;
    cin >> k;
    cin >> dr >> dc;
    int size = MatrixSize(k);
    int tr = 0, tc = 0;
    ChessBoard(tr, tc, dr, dc, size);
    size = MatrixSize(k);
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            printf("%4d", board[i][j]);
        }
        cout << endl;
    }

    return 0;
}

相關文章