回溯法解决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

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

目录
相关文章
|
8月前
|
机器学习/深度学习
【N皇后】
【N皇后】
|
5月前
|
算法
【算法学习】—n皇后问题(回溯法)
【算法学习】—n皇后问题(回溯法)
|
机器学习/深度学习
递归实现 八皇后问题(*)
递归实现 八皇后问题(*)
105 0
递归实现 八皇后问题(*)
|
11月前
|
机器学习/深度学习 存储 算法
回溯法求解N皇后问题
回溯法求解N皇后问题
84 0
|
11月前
|
机器学习/深度学习
N皇后问题
N皇后问题
50 0
|
11月前
|
机器学习/深度学习 算法 网络协议
|
机器学习/深度学习 算法 Java
回溯法
回溯法也可以叫做回溯搜索法,它是一种搜索的方式。 回溯是递归的副产品,只要有递归就会有回溯。 所以以下讲解中,回溯函数也就是递归函数,指的都是一个函数。 回溯法的效率 回溯法的性能如何呢,这里要和大家说清楚了,虽然回溯法很难,很不好理解,但是回溯法并不是什么高效的算法。 因为回溯的本质是穷举,穷举所有可能,然后选出我们想要的答案,如果想让回溯法高效一些,可以加一些剪枝的操作,但也改不了回溯法就是穷举的本质。 那么既然回溯法并不高效为什么还要用它呢? 因为没得选,一些问题能暴力搜出来就不错了,撑死了再剪枝一下,还没有更高效的解法。 此时大家应该好奇了,都什么问题,这么牛逼,只能暴力搜索。 回溯法
|
机器学习/深度学习 算法
【回溯算法篇】N皇后问题
【回溯算法篇】N皇后问题
【回溯算法篇】N皇后问题