博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
八皇后问题
阅读量:4216 次
发布时间:2019-05-26

本文共 1917 字,大约阅读时间需要 6 分钟。

package javatask;public class EightQueenO {	private int[][]map;	private int len;	private int[]C;	private int tol;	public static void main(String[] args) {		new EightQueenO().run();	}	public EightQueenO() {		len = 8;		C = new int[len];//记录当前行可放置的列		tol = 0;	}	public void run() {		search(0);		System.out.println("total = " + tol);	}	public boolean isOk(int row, int col) {			for(int j = 0; j < row; j++ ) {				if(C[j] == col || C[j]+ j == col+row || C[j]-j == col-row) {//只需要判断当前行以前的对角线和列即可					return false;				}			}		return true;	}	public void search(int cur) {		if(cur == len) {			tol++;			//只有到达 这里时候 才是完成了 八皇后 			for(int i = 0; i < len; i++ ) {				for(int j = 0; j < len; j++ ) {					if(C[i] == j)						System.out.print(1+" ");					else						System.out.print(0 +" ");				}				System.out.println();			}			System.out.println("***************");		}		else {			for(int i = 0; i < len; i++ ) {				C[cur] = i;//这里保证了 最终的值一定是构成8皇后时候的值(因为其值不断被修改直到完成所有行)				if(isOk(cur, i)) {				//	map[cur][i] = 1;//有的不能构成八皇后但是仍然 在末尾之前的位置满足 也被记录了					search(cur+1);	//所以用map记录是错误的				}			}		}//			for(int i = 0; i < len; i++ ) {//				int ok = 1;//				C[cur] = i;//				for(int j = 0; j < cur; j++ ) {//					if(C[j] == C[cur]|| C[j]+ j == C[cur]+cur || C[j]-j == C[cur]-cur) {//						ok = 0; break;//					}//				}//				if(ok == 1) search(cur+1);//			}	}}
中间的dfs部分可以换成   
for(int i = 0; i < len; i++ ) {    if(isOk(cur, i)) {     vis[cur] = i;     search(cur+1);     vis[cur] = 0;//保证 只有成功的时候才会被记录 然后 输出后 立刻 清零    }   }

C++ :

#include
using namespace std;const int N = 1010;int tol;int C[N];int n; void dfs(int cur){ if(cur == n){ tol++; return ; } else for(int j = 0; j < n; ++j){ C[cur] = j; bool ok = 1; for(int i = 0; i < cur; ++i){ if(C[cur] == C[i] || cur-C[cur] == i-C[i] || cur + C[cur] == i+C[i]){ ok = 0; break; } } if(ok) dfs(cur+1); }}int main() { cin >> n; dfs(0); cout << tol << endl; return 0; }

 

转载地址:http://roimi.baihongyu.com/

你可能感兴趣的文章
【HTML5/CSS/JS】A list of Font Awesome icons and their CSS content values(一)
查看>>
【HTML5/CSS/JS】<br>与<p>标签区别(二)
查看>>
【HTML5/CSS/JS】开发跨平台应用工具的选择(三)
查看>>
【心灵鸡汤】Give it five minutes不要让一个好主意随风而去
查看>>
【React Native】Invariant Violation: Application AwesomeProject has not been registered
查看>>
【ReactNative】真机上无法调试 could not connect to development server
查看>>
【XCode 4.6】常用快捷键 特别是格式化代码ctrl+i
查看>>
【iOS游戏开发】icon那点事 之 图标设计(三)
查看>>
【IOS游戏开发】之测试发布(Distribution)
查看>>
【IOS游戏开发】之IPA破解原理
查看>>
【一天一道LeetCode】#45. Jump Game II
查看>>
【一天一道LeetCode】#56. Merge Intervals
查看>>
【一天一道LeetCode】#58. Length of Last Word
查看>>
【一天一道LeetCode】#59. Spiral Matrix II
查看>>
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>
【一天一道LeetCode】#60. Permutation Sequence.
查看>>
【一天一道LeetCode】#118. Pascal's Triangle
查看>>
JAVA实现文件树
查看>>
ebay api GetMyMessages 函数
查看>>
手动12 - 安装php加速器 Zend OPcache
查看>>