經典八皇后算法

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
const int QUEENS = 8;
int[] QuSite = new int[QUEENS];
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Queen(0);
}
private void Queen(int n)
{
int row;
if (n == QUEENS)
{
OutputResult();
//return;
}
else
{
for ( row = 1; row <= QUEENS; row++)
{
QuSite[n] = row;
if (CanPut(n))
{
Queen(n + 1);
}
}

}

}
private bool CanPut(int n)
{
int bn;
for (bn = 0; bn < n; bn++)
{
if (QuSite[n] == QuSite[bn])
{
return false;
}
if (Math.Abs(n - bn) == Math.Abs(QuSite[bn] - QuSite[n]))
{
return false;
}

}
return true;
}
private void OutputResult()
{
Response.Write("<br><br>");
Response.Write("<table style='width: 480px; height: 389px' border='3'>");
int[] dataQueen=new int[8];
for(int j=0;j<QUEENS;j++)
{
dataQueen[QuSite[j]-1]=j;
}
for (int i = 0; i < QUEENS; i++)
{

Response.Write("<tr>");
for(int h=0;h<dataQueen[i];h++)
{
Response.Write("<td style='width: 98px; height: 21px'></td>");
}
Response.Write("<td style='width: 100px; height: 21px'><Image src='images.jpg' width='100' height='100'/></td>");
for (int k =dataQueen[i] + 1; k < QUEENS; k++)
{
Response.Write("<td style='width: 98px; height: 21px'></td>");
}


}
Response.Write("</table>");
}
}
發佈了16 篇原創文章 · 獲贊 1 · 訪問量 8128
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章