[数据结构]八皇后(暴力,解答树,DFS回溯)

来源:互联网 发布:梦幻西游手游代秒软件 编辑:程序博客网 时间:2024/06/05 15:06
/*Name:八皇后(DFS回溯)Actor:HTTime:2015年6月21日Error Reporte:}*/#include"stdio.h"#include"iostream"#include"string.h"using namespace std; #define N 8int sum;int _amap[2 * N + 1] = { 0 };int _bmap[2 * N + 1] = { 0 };//int _xmap[N + 1] = { 0 };int _ymap[N + 1] = { 0 };int bigmap[N];//写着玩void set(int x, int y, int i){_ymap[y] = i;_amap[y - x + N] = i;_bmap[y + x - 1] = i;bigmap[x] = y;//写着玩}void print()//写着玩{int i, j;for (i = 1; i <= N; i++){for (j = 1; j <= N; j++){if (bigmap[i] == j) cout << " * ";else cout << " . ";}cout << endl;}}void dfs(int x){if (x == N+1){sum++;print();//写着玩cout << endl;//写着玩}int i;for (i = 1; i <= N; i++){if (_amap[i - x + N] == 1 || _bmap[i + x - 1] == 1 || _ymap[i] == 1) continue;set(x, i, 1);dfs(x + 1);set(x, i, 0);}}int main(){sum = 0;dfs(1);cout << sum << endl;system("pause");}

0 0
原创粉丝点击