今天去面试居然被问到了8queen的问题,看过但是没有记过,而且就这个问题来说的话,能写出程序,也不能代表他真正的懂什么...当然比不会的要好很多的.然后从BAIDU找了一个程序.居然能运行.DOS界面的..
------------------居然是图论的知识,去年就是考图论的了,而且好象还有点印象,看的书是上海科技大学的.........
先把代码搞过来在具体的分析一下吧.看完侯大人的<深入浅出MFC>回头把笔记贴了.......
// Retest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#include <malloc.h>
#include <iostream>
using namespace std;
int *position; //放置的位置
int queen; //皇后数目
int count; //第N种可能性
//判断第n行是否放置皇后
bool SignPoint( int n )
{
for ( int i = 0; i < n; i++ )
{
if ( *(position + i) == *(position + n) )
{//该列已经放置过皇后了
return false;
}//if
if ( abs( *(position + i) - *(position + n) ) == n-i ) //对角线已经放置过了
{
return false;
}//if
}//for
return true;
}//Game Over
//设置皇后
void SetQueen( int n = 0 )
{
if ( queen == n )
{
//该处可以改成自己想要的显示方式
printf("NO.%d: ",++count);
printf("/n");
for ( int i=0 ; i < queen; i++ )
{
for ( int j = 0; j < queen; j++ )
{
if ( j == position[i] )
{
printf("* ");
}
else
{
printf("0 ");
}
}
printf("/n");
}
printf("/n");
return; //break
}
else
{
for ( int i = 0; i < queen; i++ )
{
position[n] = i;
if ( SignPoint(n) )//如果该位置放置皇后正确的话,则到下一行
{
SetQueen(n+1);
}
}
}
return;
}//end
int _tmain(int argc, _TCHAR* argv[])
{
cout << "请输入皇后的总数:" << endl;
cin >> queen;
position = (int*)malloc(sizeof(int));
SetQueen();
cout << "摆放完毕" << endl;
cin.get();
cin.get();
cout << "this is console program" << endl;
cin.get();
return 0;
}//Game Over
P.S:
VS2005通过了....