您的位置:首页 > 其它

棋盘摆放皇后问题(回溯思想的经典应用)

2012-08-16 12:27 375 查看
4皇后和8皇后问题是回溯思想的经典应用之一,其核心思想仍然是解空间树的深度优先搜索。今天在盲写代码过程中居然犯了糊涂而出错,后来静心下来,仔细地回顾了算法的每一步才写出了正确的代码。我的总结是,回溯算法的精髓在于确定解空间树,建立递归的开始与结束条件,为了降低时间复杂度而剪枝,回溯要返回至问题未被修改的状态。明确了上述4个问题就可以顺利地解决问题。

解空间树如下,



详细代码如下,

// QueenSettle.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#define Psize 4
using namespace std;
//decide whether to place the new queen in panel[h][w]//
inline bool IsConflict(int **panel,int len,int h, int w)
{
for (int i=0;i<h;i++)
for (int j=0;j<len;j++)
{
if (1==panel[i][j])//当前位置存在皇后则进行判断//
{
if (h==i || w==j || (h-i)==(w-j)|| (h-i)==(j-w))
return true;
}
}

return false;
};

void PlaceQueen(int **panel, int len, int h)
{
if (h>=len)
{
for (int i=0;i<len;i++)
{
for (int j=0;j<len;j++)
cout<<panel[i][j]<<"  ";
cout<<endl;
}
cout<<endl;
return;
}
for (int idx=0;idx<len;idx++)
{
if (IsConflict(panel,len,h,idx)==false)
{
panel[h][idx]=1;
PlaceQueen(panel,len,h+1);
panel[h][idx]=0;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int** panel=(int **)calloc(Psize,sizeof(int*));
for (int i=0;i<Psize;i++)
{
panel[i]=(int *)calloc(Psize,sizeof(int));
}
PlaceQueen(panel,Psize,0);
for (int i=0;i<Psize;i++)
{
free(panel[i]);panel[i]=NULL;
}
free(panel);panel=NULL;
return 0;
}

运行结果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: