zoukankan      html  css  js  c++  java
  • 八皇后算法与实现(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;
    }

  • 相关阅读:
    Maven笔记(一)
    Oracle JDBC通过占位符可以查询可变长字段,不可查询固定长度字段
    Oracle 汉字在不同字符集下所占字节
    Spring Bean注册解析(一)
    Spring AOP切点表达式用法总结
    ThreadPoolExecutor详解
    数据库索引创建与优化
    ScheduledThreadPoolExecutor详解
    使用三种方法求解前N个正整数的排列
    后缀表达式的计算
  • 原文地址:https://www.cnblogs.com/vedgtar/p/2176170.html
Copyright © 2011-2022 走看看