一直都是用深搜求八皇后问题,昨天面向对象老师讲了一下用面向对象思想来写,感到质疑,回来写了一下,感觉恶心。
这是人类的思想吗?
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<string>
using namespace std;
#define N 8
class Queen
{
const int col;
int row;
bool testAttack(int testrow, int testcol)
{
if(testrow == row)return true;
if(abs(testrow-row) == abs(testcol - col))return true;
return false;
}
public:
Queen(int c, int r, Queen *n):col(c), row(r), neighbor(n){};
void show()
{
printf("row = %d col = %d\n", row, col);
if(neighbor) neighbor->show();
}
Queen *neighbor;
bool findsolution();
bool canAttack(int , int);
bool advance();
};
bool Queen::findsolution()
{
while(neighbor && neighbor->canAttack(row, col))
{
if(!advance())
return false;
}
return true;
}
bool Queen::advance()
{
while(row < N)
{
row ++;
return findsolution();
}
if(neighbor && !neighbor->advance())
return false;
if(row == N && col == 1)return false;
row = 1;
return findsolution();
}
bool Queen::canAttack(int testrow, int testcol)
{
if(testAttack(testrow, testcol))
return true;
return neighbor && neighbor->canAttack(testrow, testcol);
}
int main()
{
Queen *lastqueen = 0;
for(int i = 1; i <= N; i++)
{
lastqueen = new Queen(i, 1, lastqueen);
if(!lastqueen->findsolution())printf("nosolution\n");
else if(i == N)
{
lastqueen->show();
while(lastqueen->advance())lastqueen->show();
}
}
return 0;
}