【www.gdgbn.com--ios】


#include"stdio.h"
#define N 8          //因为算出来的数据太大,所以要算很久,可以改变N的值进行测试。
#include"iostream.h" //此算法采用回溯法

enum bin{fal,tr};    //如果有更好的算法,请发e-mail给我。在此谢过。
int top=0;
long int num=0;
int row[]={-1,-2,-2,-1,1,2,2,1};
int col[]={-2,-1,1,2,2,1,-1,-2};
bin mark[N][N];

struct stack
{
  int x,y;
  int dir;}board[N*N];

void push(stack it)
{
  board[top].x=it.x;
  board[top].y=it.y;
  board[top].dir=it.dir;
  mark[board[top].x][board[top].y]=tr;
  top++;
  }
 
stack pop()
{
  --top;
  mark[board[top].x][board[top].y]=fal;
  board[top].dir++;
  return board[top];
  }
 
bin empty()
{
  if(top==0) return tr;
  else return fal;
  }
 
void main()
{
  stack temp={N-1,N-1,-1};
  push(temp);
  while(!empty())
  {
    int g,h;
    temp=pop();
    int i=temp.x;
    int j=temp.y;
    int dir=temp.dir;
    while(dir<8)
    {
      g=i+row[dir];
      h=j+col[dir];
      if((g<0)||(h<0)||(g>=N)||(h>=N)||mark[g][h]) dir++;
      else {
             if(g==0&&h==0) {num++;dir++;}
             else {
                   temp.x=i;
                   temp.y=j;
                   temp.dir=dir;
                   push(temp);
                &n

本文来源:http://www.gdgbn.com/shoujikaifa/13122/