昨天晚上写的八皇后问题,原题目看摘要吧:主要利用递归到最深层后然后逐层回溯,在写完这个算法时,想了一个问题:如何在中途中断递归,直接跳出递归,网上有人说用goto,各说纷纭,不过我觉得直接设置一个bool变量,在要中断时设置bool,然后检测其值就应该可以了,不过还是要逐层返回,以后想到更好的再说.
源程序;cpp文件:
#include"8Queen.h"
void main()
{
char ChessBoard[8][8]; //定义棋盘
{
for(int i = 0;i<8;i++)
{
for(int j = 0;j<8;j++)
{
ChessBoard[i][j] = '*';
}
}
}
int x = 1;
Queen(ChessBoard,0,0,x);
}
头文件 8Queen.h
#include<iostream>
using namespace std;
bool Check_Row(char ChessBoard[][8],int row,int col) //检查行
{
for(int i = 0;i<8;i++)
{
if(ChessBoard[row][i] != '*')
{
return false;
}
}
return true;
}
bool Check_Col(char ChessBoard[][8],int row,int col) //检查列
{
for(int i = 0;i<8;i++)
{
if(ChessBoard[i][col] != '*')
{
return false;
}
}
return true;
}
bool Check_bias(char ChessBoard[][8],int row,int col) //检查对角线
{
int i = row;
int j = col;
if(ChessBoard[i][j] != '*')
{
return false;
}
while((i>0)&&(j>0))
{
i--;
j--;
if(ChessBoard[i][j] != '*')
return false;
}
i = row;
j = col;
while((i<7)&&(j>0))
{
i++;
j--;
if(ChessBoard[i][j] != '*')
return false;
}
i = row;
j = col;
while((i<7)&&(j<7))
{
i++;
j++;
if(ChessBoard[i][j] != '*')
return false;
}
i = row;
j = col;
while((i>0)&&(j<7))
{
i--;
j++;
if(ChessBoard[i][j] != '*')
return false;
}
return true;
}
void output(char chess[][8])
{
for(int i = 0;i<8;i++)
{
cout<<"("<<i<<")";
for(int j = 0;j<8;j++)
{
cout<<chess[i][j]<<" ";
}
cout<<endl;
}
}
void Queen(char Chess_Board[][8],int row,int col,int &x)
{
if(row == 8)
{
cout<<"< "<<x<<" >"<<"**************************************"<<endl;
output(Chess_Board);
x++;
}
else
{
int a,b;
a = row;
b = col;
if(Check_Row(Chess_Board,a,b)&&Check_Col(Chess_Board,a,b)&&Check_bias(Chess_Board,a,b))
{
Chess_Board[a][b] = '@';
Queen(Chess_Board,a+1,0,x);
Chess_Board[a][b] = '*';
if(b<7)
{
Queen(Chess_Board,a,b+1,x);
}
}
else
{
if(b<7)
{
Queen(Chess_Board,a,b+1,x);
}
}
}
}