现在的位置: 首页 > 综合 > 正文

经典八皇后问题;

2013年10月16日 ⁄ 综合 ⁄ 共 1075字 ⁄ 字号 评论关闭

 贴个八皇后的代码, 免得以后忘了,呵呵。

 

 #include "stdio.h"

 

int Total = 0;

typedef struct tag_Quiz
{
 int Steps;  // 0, 1, 2, 3, 4,  5, 6, 7, 8
 int Chose[8]; 
} Quiz;

int CheckMap(Quiz Map)
{
 /*  check the last step */
 int i;
 

 if (Map.Steps == 1)
 {
  return 1;
 }

 for (i = 0; i < Map.Steps -1; i++)
 {
  /* check Map.Chose[i]  and Map.Chose[Map.Steps-1] */
  if ( Map.Chose[i] == Map.Chose[Map.Steps-1])
  {
   return 0;
  }

  if ( abs(Map.Chose[i] - Map.Chose[Map.Steps-1]) ==
   abs(Map.Steps - 1 - i) )
  {
   return 0;
  }
 }

 return 1;
}

 

void Queen4(Quiz Map)
{

 /******************************** Print Map ****************/
 int  i;
 char*   Info[8] = {
      "# 0 0 0 0 0 0 0 /n",
      "0 # 0 0 0 0 0 0 /n",
      "0 0 # 0 0 0 0 0 /n",
      "0 0 0 # 0 0 0 0 /n",
      "0 0 0 0 # 0 0 0 /n",
      "0 0 0 0 0 # 0 0 /n",
      "0 0 0 0 0 0 # 0 /n",
      "0 0 0 0 0 0 0 # /n",
       };
 int oldStep = Map.Steps;

 if (Map.Steps == 8)
 {
  printf("/nMap Layout <%d> : /n", ++Total);
  // printf Map;
  for (i = 0; i < 8; i++)
  {
   printf(Info[Map.Chose[i]]);
  }
  return ;
 }

 
 
 Map.Steps++;
 for ( i = 0; i < 8; i++)
 {
  Map.Chose[Map.Steps -1] = i;
  if (CheckMap(Map))
  {
   Queen4(Map);
  }
 }
}

 

void
main(
  void
  )
{
 Quiz puzz;
 puzz.Steps = 0;
 Queen4(puzz);

 printf("/n/nTotal Array ==> %d /n", Total);

 return 0;
}

抱歉!评论已关闭.