ChessMetric - 2003 TCCC Round 4

本文介绍了一种算法,用于计算特定大小的棋盘上,国王骑士从起始位置到达目标位置的不同路径数量。国王骑士可以进行单步移动或L形跳跃。文章提供了一个C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Problem Statement

     Suppose you had an n by n chess board and a super piece called a kingknight. Using only one move the kingknight denoted 'K' below can reach any of the spaces denoted 'X' or 'L' below:   .......
   ..L.L..
   .LXXXL.
   ..XKX..
   .LXXXL.
   ..L.L..
   .......

In other words, the kingknight can move either one space in any direction (vertical, horizontal or diagonally) or can make an 'L' shaped move. An 'L' shaped move involves moving 2 spaces horizontally then 1 space vertically or 2 spaces vertically then 1 space horizontally. In the drawing above, the 'L' shaped moves are marked with 'L's whereas the one space moves are marked with 'X's. In addition, a kingknight may never jump off the board.


 Given the size of the board, the start position of the kingknight and the end position of the kingknight, your method will return how many possible ways there are of getting from start to end in exactly numMoves moves. start and finish are int[]s each containing 2 elements. The first element will be the (0-based) row position and the second will be the (0-based) column position. Rows and columns will increment down and to the right respectively. The board itself will have rows and columns ranging from 0 to size-1 inclusive.


 Note, two ways of getting from start to end are distinct if their respective move sequences differ in any way. In addition, you are allowed to use spaces on the board (including start and finish) repeatedly during a particular path from start to finish. We will ensure that the total number of paths is less than or equal to 2^63-1 (the upper bound for a long).


#include <stdlib.h>
#include <string.h>
#include <iostream>

#define N 105
#define M 55
using namespace std;

long long dp[N][N][M];
int s;
int d[16][2] = {0, 1, 0, -1, -1, 0, 1, 0, -1, 1, 1, 1, -1, -1, 1, -1, 1, 2, -1, 2, 2, 1, -2, 1, 1, -2, -1, -2, 2, -1, -2, -1};
int sr, sc;

int DP(int r, int c, int n)
{
    if(n == 0)
    {
        if(r == sr && c == sc)
            return 1;
        else
            return 0;
    }

    if(dp[r][c][n] != -1)
        return dp[r][c][n];

    int an = 0;
    for(int i = 0; i < 16; i++)
    {
        int rr = r + d[i][0];
        int cc = c + d[i][1];

        if(rr >= 0 && rr < s && cc >= 0 && cc < s)
        {
            an += DP(rr, cc, n-1);
        }
    }
    dp[r][c][n] = an;
    return an;
}

long long howMany(int size, int start[], int end[], int numMoves)
{
    sr = start[0];
    sc = start[1];
    s = size;
    memset(dp, -1, sizeof(dp));
    return DP(end[0], end[1], numMoves);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值