#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
int n,count;
int **Game;
int *chess_board;
QLabel *input,*output;
QLineEdit *edit;
QPushButton *btnOK;
void init();
void Resolve(int t);
bool isOK(int t);
bool flag;
void paintEvent(QPaintEvent *);
public slots:
void display();
};
#endif// MAINWINDOW_H
#include "mainwindow.h"
#include <QPainter>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
//this->setFixedSize( this->width (),this->height ());
setMinimumSize(600,450);
setMaximumSize(600,450);
setWindowTitle(tr("n皇后问题"));
input = new QLabel(this);
input->setGeometry(400,60,150,70);
input->setText("请输入皇后个数:");
edit = new QLineEdit(this);
edit->setGeometry(400,60+70+7,100,30);
btnOK = new QPushButton(this);
connect(btnOK,SIGNAL(clicked()),this,SLOT(display()));
btnOK->setGeometry(400,60+140+14,100,30);
btnOK->setText("确定");
output = new QLabel(this);
output->setGeometry(400,60+210+21,100,30);
output->setText("解个数:");
n=5;count=0;
Game = new int*[n];
for(int i=0;i<n;i++) Game[i] = new int[n];
chess_board = new int[n];
for(int i=0;i<n;i++) chess_board[i]=1<<10;
init();
}
MainWindow::~MainWindow()
{
}
void MainWindow::init(){
for(int i=0;i<n;i++){ //初始化
for(int j=0;j<n;j++){
if(i==j||(j-i)%2==0||(i-j)%2==0){
Game[i][j]=1;
}
else
Game[i][j]=2;
}
}
}
//#define PAINT(pixmap) painter.drawPixmap(50+300/n,60+300/n,300/n,300/n,pixmap)
void MainWindow::paintEvent(QPaintEvent *) {
QPainter painter(this);
QPixmap map1("://1.png");
QPixmap map2("://2.png");
QPixmap map0("://queen.png");
//painter.drawPixmap(50,60,300,300,map1);
//PAINT(map1);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(Game[i][j]==1) painter.drawPixmap(50+j*300/n,60+i*300/n,300/n,300/n,map1);
else if(Game[i][j]==2) painter.drawPixmap(50+j*300/n,60+i*300/n,300/n,300/n,map2);
else if(Game[i][j]==3) painter.drawPixmap(50+j*300/n,60+i*300/n,300/n,300/n,map0);
}
}
}
void MainWindow::display(){
n = edit->text().toInt();
Game = new int*[n];
for(int i=0;i<n;i++) Game[i] = new int[n];
init();
Resolve(0);
//qDebug()<<count;
output->setText("解个数为: "+QString::number(count));
repaint(); //调用paintEvent函数画图
count=0;
}
void MainWindow::Resolve(int t){ //回溯法求解,并修改Game数组的值
if(t!=n){
for(int position=0;position<n;position++){
chess_board[t]=position; //第t层皇后的位置下标
if(isOK(t)){
qDebug()<<t+1<<","<<chess_board[t]+1;
if(t==n-1) flag=true;
else flag=false;
t+=1;
Resolve(t);
t-=1;
}
}
}
else if(flag==true&&t==n){
qDebug()<<888; //标记此次搜索结束
count++;
init();
for(int i=0;i<n;i++){
Game[i][chess_board[i]]=3;
}
qDebug()<<count;
}
}
bool MainWindow::isOK(int t){
for(int i=0;i<t;i++){
if(chess_board[t] == chess_board[i] || abs(chess_board[i] - chess_board[t]) == abs(t - i)) return false;
}
return true;
}