C - 骑士在无限棋盘上可以从(xa,ya)到(xb,yb)制作的所有长度为n的路线

时间:2014-10-15 08:38:24

标签: c recursion

在给定起始坐标,结束坐标,无限棋盘以及路线长度必须为n步的情况下,计算骑士可能采取的唯一路线数量的最有效方法是什么?

根据速度测试,我目前的速度还不够快。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int checkColor(int a, int b) {
  if ((((a % 2 == 0) || (a == 0)) && ((b % 2 == 0) || (b == 0))) || a == b) {
    return 0;
  }
  return 1;
}
int checkInsuficientDistance(int n, int xb, int yb, int xe, int ye) {
  return 5 * n * n < (pow((xe - xb), 2) + pow((ye - yb), 2));
}
int numRoutes(int xb, int yb, int xe, int ye, int n) {
  if(n == 0){
    if(!(xe == xb && ye == yb)){
      return 0;
    }else{
      return 1;
    }
  }   
  if (checkInsuficientDistance(n, xb, yb, xe, ye)) {
    return 0;
  }
  int totalRoutes = 0;
  totalRoutes += numRoutes(xb + 2, yb + 1, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb + 2, yb - 1, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb - 2, yb + 1, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb - 2, yb - 1, xe, ye, n - 1 );

  totalRoutes += numRoutes(xb + 1, yb + 2, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb - 1, yb + 2, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb + 1, yb - 2, xe, ye, n - 1 );
  totalRoutes += numRoutes(xb - 1, yb - 2, xe, ye, n - 1 );
  return totalRoutes;
}

int main(int argc, char* argv[]) {
  int xb, yb, xe, ye, length;
  printf("Start coordinate: ");
  scanf("%d %d", &xb, &yb);

  printf("End coordinate: ");
  scanf("%d %d", &xe, &ye);

  printf("Length: ");
  scanf("%d", &length);

  if ((checkColor(xb, yb) == checkColor(xe, ye)) && length % 2 != 0) {
    printf("\nNumber of routes: 0\n");
  }else{
    printf("\nNumber of routes: %d\n", numRoutes(xb, yb, xe, ye, length));
  }
  return 0;
}

0 个答案:

没有答案