回溯法解决N皇后问题

简介: 来源:维基百科-N皇后问题解题思路采用回溯法,即逐一位置放置,然后放置下一行,如果下一行没有合法位置,则回溯到上一行,调整位置,直到得到所有值.实现代码/** * solve the N-Queen problem */public class NQueen { //the ...

来源:

维基百科-N皇后问题

解题思路

采用回溯法,即逐一位置放置,然后放置下一行,如果下一行没有合法位置,则回溯到上一行,调整位置,直到得到所有值.

实现代码

/**
 * solve the N-Queen problem
 */
public class NQueen {

  //the number of chess board,example 8
  private static final int N = 8;

  // result, the result[i] mean: the location of [i] line is on result[i] column.
  private int[] result = new int[N];

  //total num of possible result
  private int resultNum = 0;

  /**
   * calculation
   */
  private void calculation(int n) {

    //if n == N, print the result
    if (n == N) {
      for (int i = 0; i < result.length; i++) {
        System.out.print(result[i] + ",");
      }
      System.out.println();
      resultNum++;
    } else {
      for (int i = 0; i < N; i++) {
        // test every location possible
        result[n] = i;
        //if line n is allowed, locate the next line
        if (isAllowed(n)) {
          calculation(n + 1);
        }
      }
    }
  }

  /**
   * judge current line is allowed or not.
   */
  private boolean isAllowed(int i) {
    // i is not allowed while it in same line or diagonal with the pre line
    for (int j = 0; j < i; j++) {
      if (result[i] == result[j] || Math.abs(i - j) == Math.abs(result[i] - result[j])) {
        return false;
      }
    }
    return true;
  }

  //main method, include some test cases
  public static void main(String[] args) {
    NQueen queen = new NQueen();

    queen.calculation(0);

    System.out.println(queen.resultNum);
  }

}

完。







ChangeLog


2019-02-24 完成



以上皆为个人所思所得,如有错误欢迎评论区指正。

欢迎转载,烦请署名并保留原文链接。

联系邮箱:huyanshi2580@gmail.com

更多学习笔记见个人博客------>呼延十

目录
相关文章
|
3月前
|
消息中间件 Kubernetes NoSQL
动态规划-状态压缩、树形DP问题总结
动态规划-状态压缩、树形DP问题总结
|
4月前
|
算法
【算法学习】—n皇后问题(回溯法)
【算法学习】—n皇后问题(回溯法)
|
10月前
|
机器学习/深度学习 存储 算法
回溯法求解N皇后问题
回溯法求解N皇后问题
84 0
|
10月前
|
机器学习/深度学习 算法 网络协议
|
人工智能 算法 搜索推荐
LeetCode 周赛 338,贪心 / 埃氏筛 / 欧氏线性筛 / 前缀和 / 二分查找 / 拓扑排序
大家好,我是小彭。 上周末是 LeetCode 第 338 场周赛,你参加了吗?这场周赛覆盖的知识点很多,第四题称得上是近期几场周赛的天花板。
80 0
|
算法
【算法】 八皇后问题之回溯法
会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。每次填满第一行第一列,当不满足时候,试下第一行第二列,依次进行,递归的出口为找到第八个点,跳出递归。,在循环里面还要判断是否满足不同行,不同列,不同对角线。使用回溯法来解决该问题,下面的代码是我看到过的最精简的代码,相关的注释都写在代码上了。运行得出结果,总共有92中结果。
209 0
|
机器学习/深度学习 算法
【回溯算法篇】N皇后问题
【回溯算法篇】N皇后问题
【回溯算法篇】N皇后问题
|
算法 Java
【递归与回溯算法】汉诺塔与八皇后问题详解
文章目录 1 汉诺塔问题 1.1 汉诺塔问题概述 1.2 思路分析 1.3 代码实现(Java) 1.4 结果验证 2 八皇后问题 2.1 八皇后问题概述 2.2 思路分析 2.2.1 问题划分与分析 2.2.2 涉及到的数据结构分析 2.2.3 上下对角线与行列的关系 2.3 代码实现(Java) 2.4 结果验证
【递归与回溯算法】汉诺塔与八皇后问题详解