算法分析作业,要求图形化输入N皇后的解. 应付下作业,代码质量一般.
下面是部分源码
#define PIXLEN 50
BOOL place(int x[],int k)
{
int i;
for (i=1;i<k;i++)
if ( (x[i]==x[k]) || (abs(x[i]-x[k])==abs(i-k)) )
return FALSE;
return TRUE;
}
void CqueenView::xPrint(int x[],int n,int count,BOOL bDraw)
{
static int bContinue=TRUE;
if (bDraw)
{
if ((bContinue) && MessageBox(_T("是否逐个放置皇后?"),_T("Hint"),MB_OKCANCEL)==IDOK)
{
MyRefreshWin();
DrawQueenFrame(m_queenNum);
for (int i=1;i<=n;i++)
{
Sleep(200);
MySetPixel(x[i],i);
}
}
else bContinue=FALSE;//第一次不放置,下次就不再询问了
return;
}
bContinue=TRUE;
CString text;
text.Format(_T("第%2d个结果: "),count);
for (int i=1;i<=n;i++)
{
CString temp;
temp.Format(_T("%d "),x[i]);
text=text+temp;
}
HDC hdc;
hdc = ::GetDC(m_hWnd);
count--;
TextOut(hdc,((count)%5)*text.GetLength()*8,((count/5)+1)*25,text,text.GetLength());
::ReleaseDC(m_hWnd,hdc);
}
void CqueenView::n_queens(int n,int x[],BOOL bDraw)
{
int k=1,resultCount=0;
x[1]=0;
while (k>0)
{
x[k]=x[k]+1;
while ((x[k]<=n) && (!place(x,k)))
x[k]++;
if (x[k]<=n){
if (k==n){
resultCount++;
xPrint(x,n,resultCount,bDraw);
x[k]=0;
k=k-1;
}
else {
k++;x[k]=0;
}
}
else{
x[k]=0;k=k-1;
}
}
}
void CqueenView::DrawQueenFrame(int n) //画棋盘
{
HDC hdc;
hdc = ::GetDC(m_hWnd);
for (int i=0;i<=n;i++)
{
int x,y;
x=i*PIXLEN; y=0;
MoveToEx(hdc,x,y,NULL);
LineTo(hdc,x,n*PIXLEN);
}
for (int i=0;i<=n;i++)
{
int x,y;
x=0; y=i*PIXLEN;
MoveToEx(hdc,x,y,NULL);
LineTo(hdc,n*PIXLEN,y);
}
::ReleaseDC(m_hWnd,hdc);
}
void CqueenView::MySetPixel(int x,int y)
{
HDC hdc;
hdc = ::GetDC(m_hWnd);
for (int i=(x-1)*PIXLEN+1;i<=(x-1)*PIXLEN+PIXLEN;i++)
for (int j=(y-1)*PIXLEN+1;j<=(y-1)*PIXLEN+PIXLEN;j++){
SetPixel(hdc,i,j,RGB(200,00,0));
}
::ReleaseDC(m_hWnd,hdc);
}
void CqueenView::SelOutput(BOOL bDraw)
{
if (!bDraw){
CDlgGetN dlg;
if (dlg.DoModal()!=IDOK) return;
m_queenNum=dlg.m_queenNum;
}
if (m_queenNum==0) return;
MyRefreshWin();
int *x=new int[m_queenNum+1];
n_queens(m_queenNum,x,bDraw);
delete []x;
}
void CqueenView::OnOutput()
{
SelOutput(FALSE);
}
void CqueenView::OnDrawresult()
{
SelOutput(TRUE);
}
void CqueenView::MyRefreshWin()//刷新窗口
{
Invalidate();
UpdateWindow();
}