JAVA实现N皇后问题(回溯法)
生活随笔
收集整理的這篇文章主要介紹了
JAVA实现N皇后问题(回溯法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.leetCode;
/***
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.* @author Zealot* @date 2015年7月23日 下午6:14:49*/
public class NQueensII {int[] x;//當前解 int N;//皇后個數int sum = 0;//當前已找到的可行方案數public int totalNQueens(int n) {N = n;x = new int[N+1];backTrace(1);return sum;}/*** col行這個點,x[col]列這個點。與已經存在的幾個皇后。是否符合要求,放到這個位置上,* @param col* @return*/private boolean place(int col){for(int i = 1; i < col; i++){if(Math.abs(col - i)==Math.abs(x[col]-x[i])||x[col]==x[i]){return false;}}return true;}private void backTrace(int t) {if(t>N){sum++;}else {//第t行。遍歷全部的節點for(int j = 1; j <= N; j++) {x[t] = j ;//假設第j個節點能夠放下皇后if(place(t)){//接著放下一個backTrace(t+1);}}}}public static void main(String[] args) {NQueensII n = new NQueensII();System.out.println(n.totalNQueens(8));}
}
總結
以上是生活随笔為你收集整理的JAVA实现N皇后问题(回溯法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你真的在正确地使用WLAN控制器吗?
- 下一篇: QD75运动模块使用