八皇后算法与实现(C)

当在百度里搜索“八皇后”, 会提供很多种在不同语言下的算法与实现。

数据结构与算法一直是我的一块心病, 然后我努力的治疗。

一.采用递归方式实现。

算法思想:

在第n行(令从第一行开始)的第一个位置开始放置第n个皇后,然后进行验证是否满足:

1.是否与前n-1个皇后都不在同一列(肯定已经不再一行,因为是一行一行的比较的);

2.不再同一条斜线上(斜率为1或 -1)。

验证成功,则放置第n+1个皇后。

知道n为9时,此时八个皇后已经全部放完,可以打印出来。

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

#define N 8

int   Grid[N][N];

void OutPut()
{
 static int count = 1;
 int i=0;
 printf("Router %d:\n",count++);
 for(i=0;i<N;i++)
 {
  int j=0;  
  for(j=0;j<N;j++)
  {
   printf("%d ",Grid[i][j]);
  }  
  printf("\n");
 }
 
}

int Valid(int n,int col)
{
 int rank=0;
 for(rank=0;rank<n;rank++)
 {
  int j = 0;
  while(Grid[rank][j] != 1)
  {
   j++;
  }

  if(j == col)//in one line
  {
   return 0;
  }

  if((col-j) == (n-rank)||(col-j) == (rank-n))//in an oblique line
  {
   return 0;
  }
 }
 return 1;
}

void Queen(int n)
{
 int col;

 if(n == 8)
 {
  OutPut();
  return;
 }

 for(col=0;col<N;col++)
 {
  Grid[n][col] = 1;
  if(Valid(n,col))
  {
   Queen(n+1);
  } 
  Grid[n][col] = 0;//clear the queen when roll back
 }
}

int main(void)
{
 Queen(0);
 return 0;
}

posted on 2011-09-14 14:35  影一辉  阅读(623)  评论(0编辑  收藏  举报