惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
M
MIT News - Artificial intelligence
Y
Y Combinator Blog
L
LangChain Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
IT之家
IT之家
A
About on SuperTechFans
H
Help Net Security

博客园 - gxc

C#2.0中的泛型约束(转载) 解决‘“System.Configuration.ConfigurationSettings.AppSettings”已过时’的警告 《雷神之锤III》里求平方根倒数的函数 回溯法(vc)百鸡百钱问题 六十六条经典禅语 prototype.js和Ajax 悖论 标签的使用(2) 标签的使用(1) 自底向上的归并排序 自顶向下的归并排序 归并排序之归并算法 Josephus问题(循环链表) 找质数算法(Sieve of Eratosthenes筛法) 堆排序 直接选择排序 快速排序算法 Some of the new features from ASP.NET 2.0 在ASP.NET中使用AJAX
回溯法(vc)八皇后问题
gxc · 2007-02-02 · via 博客园 - gxc

伪代码:
int m=0,ok=1;//空状态是一个合理情况
int n=8;
do
{
   if(ok)
      if(m==n)
      {
            输出解;
            调整;
      }
      else 扩展;
   else 调整;
   ok=前m个的合理性;
}while(m!=0);

#include <iostream.h>

#define N 8

void main()
{    
    
int n=N-1;        //最后行(列)数
    int good=1;        //合理性
    int m=0;        //搜索列数
    int col[N];        //c[k]表示第c[k]行第k列放置皇后
    int a[N];        //a[k]=1表示第k行没有皇后
    int b[2*N-1];    //b[k]=1表示第k条反斜线没有皇后
    int c[2*N-1];    //c[k]=1表示第k条斜线没有皇后
    col[0]=0;
    
for(int i=0;i<N;i++)
    
{
        a[i]
=1;
    }

    
for(i=0;i<2*N-1;i++)
    
{
        b[i]
=c[i]=1;
    }

    
do
    
{
        
if(good)
        
{
            
if(m==n)
            
{
                
//output
                cout<<"/////////其中一个解答///////////"<<endl;                    
                
for(int r=0;r<N;r++)
                
{
                    
for(int l=0;l<N;l++)
                        
if(col[l]==r)
                            cout
<<" Q ";
                        
else
                            cout
<<" * ";
                    cout
<<"\n";
                }


                
                
//调整找下一个
                while(col[m]==n)
                
{
                    m
--;
                    a[col[m]]
=b[m+col[m]]=c[m+n-col[m]]=1;
                }

                col[m]
++;
            }

            
else
            
{
                
//扩展
                a[col[m]]=b[m+col[m]]=c[m+n-col[m]]=0;
                col[
++m]=1;
            }

        }

        
else
        
{
            
//调整
            while(col[m]==n)
            
{
                m
--;
                a[col[m]]
=b[m+col[m]]=c[m+n-col[m]]=1;
            }

            col[m]
++;
        }

        good
=a[col[m]]&&b[m+col[m]]&&c[m+n-col[m]];//检查合理性
    }
while(m!=0);
}