using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace eightqueen
{
class Queen
{
private int row;
private int column;
private Queen neightbor;
//初始化
public Queen(int c, Queen n)
{
row =1;
column = c;
neightbor = n;
}
//找到解决方案
public Boolean findSolution()
{
while (neightbor != null && neightbor.canAttack(row, column))
if(!advance ()) return false;
return true;
}
//前进到下一位置
public Boolean advance()
{
if (row < 8)
{
row += 1;
return this.findSolution();
}
if (neightbor != null && !neightbor.advance())
{
return false ;
}
row = 1;
return this.findSolution();
}
//使用生产器,生成所有可能的部分解决方案和过滤掉无法实现最终目标的解决方案
private Boolean canAttack(int testRow, int testColumn)
{
if (row == testRow) return true;
//测试对角线
int columnDifference = testColumn - column;
if ((row+columnDifference ==testRow ) || (row-columnDifference ==testRow ))
return true ;
return neightbor != null && neightbor.canAttack(testRow, testColumn);
}
public void print()
{
if (neightbor != null)
neightbor.print();
Getcolumnrow += "column:" + column.ToString () +";row:" + row.ToString () +"/n";
}
private static string Getcolumnrow="";
public string getcolumnrow()
{
return Getcolumnrow ; }
}
}
在窗体中建立一个textbox1
调用类
private void Form1_Load(object sender, EventArgs e)
{
Queen lastqueen = null;
for (int i = 1; i <= 8; i++)
{
lastqueen = new Queen(i, lastqueen);
if (!lastqueen.findSolution())
MessageBox.Show("no solution/n");
}
lastqueen.print();
textBox1.Text = lastqueen.getcolumnrow();
}