八皇后问题问题描述:
八皇后问题是一个古老而著名的问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
C#算法的解决方法:
public class Queen
{
public Queen()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private static bool[] columflag=new bool[8]{true,
true,true,true,true,true,true,true};//列占用标记 true为可用
private static bool[] leftflag=new bool[15]{true,true,true,
true,true,true,true,true,true,true,true,true,true,true,true};//左行对角线占用标记
private static bool[] rightflag=new bool[15]{true,true,
true,true,true,true,true,true,true,true,true,true,true,true,true};//右行对角线占用标记
private static int[,] position=new int[,]{{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
};//皇后位置坐标
private static int sum=0;
public static void TryStep(int i)//i取值1至8
{
for (int j=1;j<=8;j++)
{
if (columflag[j-1]&&leftflag[i+j-2]&&rightflag[i-j+7])//如果当前位置可以放置
{
columflag[j-1]=false;
leftflag[i+j-2]=false;
rightflag[i-j+7]=false;//占用
position[i-1,j-1]=1;//加入皇后位置
if (i<8)
{
TryStep(i+1);//进入下一行
}
else
{
sum++;//解法数统计
Console.WriteLine("");
Console.WriteLine("第 {0} 种解法:",sum);
Console.WriteLine("");
for (int m=0;m<8;m++) //打印解法
{
for (int n=0;n<8;n++)
{
Console.Write("{0} ",position[m,n]);
}
Console.Write("\n");
}
}
columflag[j-1]=true;//如果不能放置时,取消占座及移走皇后
leftflag[i+j-2]=true;
rightflag[i-j+7]=true;
position[i-1,j-1]=0;
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
C#算法巧解八皇后问题就向你介绍到这里,希望通过这个例子使你对C#算法有一点认识。
【编辑推荐】