您的位置:首页 > 编程语言 > C#

【经典算法】八皇后问题C#版

2016-05-26 03:33 417 查看
八皇后问题是一个比较经典的算法题目,记得大二的时候,自己在寝室折腾出来的,现在把他放出来。

关于八皇后

八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。计算机发明后,有多种计算机语言可以解决此问题。

程序大致分为两块:

一个是四皇后游戏

另一个是八皇后(可扩充,个数不为8)

如下图菜单页面:



我们先看四皇后游戏模块(可以从下图看出,有对角线情况,故队形不服合):



下图合格(无对角线及同行同列情况,合格):



接着,我们来看看八皇后问题(下图是八皇后问题中的其中一个解):



针对八皇后问题的扩充,我们将设置为6,如下图:



以下代码是大二时候写的,难免有点“烂”,勿喷。

先来看看四皇后游戏,如下:

bool res=true;
if (cli_nnumber < 4)
{
MessageBox.Show("请选定四个格子");
}
else
{
for (int i = 0; i < 4; i++)//行
{
for (int j = i+1; j < 4; j++)//列
{
if (Qs[i] == Qs[j])//同列
{
MessageBox.Show("Game Over,存在同列情况");
label1.Controls.Clear();
res = false;
}
if (Math.Abs(i - j) == Math.Abs(Qs[i] - Qs[j]))
{
MessageBox.Show("Game Over,存在对角线情况");
label1.Controls.Clear();
res = false;
}

}
}
if (res == true)
{
MessageBox.Show("成功");
}

}


再者看八皇后:

button2.Text = "下一组解";
bool bl = true;
Queen qu = new Queen(SIZE);
int total = 0;
ArrayList tb = qu.Arrang(out total);
MessageBox.Show("共有" + total.ToString() + "组解");
Graphics graphics = this.panel2.CreateGraphics();
// Opaque red, width 5
Pen pen = new Pen(Color.Red, 5);
// Opaque aqua
SolidBrush brush = new SolidBrush(Color.FromArgb(255, 180, 255, 255));
this.panel2.Controls.Clear();
while (bl)
{
for (int i = 0; i < tb.Count; i++)
{
int M = i + 1;
string[,] arr = (string[,])tb[i];
for (int j = 0; j < SIZE; j++)
{
for (int k = 0; k < SIZE; k++)
{
if (arr[j, k].ToString() == "Q")//合适位置
{
System.Windows.Forms.PictureBox box = new PictureBox();
box.SetBounds(((j ) * 400 / SIZE), (k ) * 400 / SIZE, 400 / SIZE, 400 / SIZE);
Image img = Image.FromFile(System.Environment.CurrentDirectory + "//b.jpg");
System.Drawing.Bitmap btm = new Bitmap(img, 400 / SIZE, 400 / SIZE);
box.Image = btm;
this.panel2.Controls.Add(box);
}
}
}
if (M + 1 <= total)//下一组解
{
label2.Text = "第" + (M + 1).ToString() + "次解";
if (MessageBox.Show("第" + (M + 1) + "次解,是否继续","提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
button2.Text = "开始";
bl = false;
goto A;
}
this.panel2.Controls.Clear();
}
else
{
bl = false;
}

}
A: ;
}


现在看之前的代码,确实很烂!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  八皇后 算法 c#