首页 > 学院 > 开发设计 > 正文

求从棋盘的坐下角到右上角的无环路的总数

2019-11-17 05:33:12
字体:
来源:转载
供稿:网友
#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);
                   i=g;
                   j=h;
                   dir=0;
                   }//else
             }//else
      }//while
    }//while
  cout<<"the total number is:"<<num;
  getchar();
  }//main


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表