递归算法学习系列之八皇后问题

1.引子

   中国有一句古话,叫做“不撞南墙不回头",生动的说明了一个人的固执,有点贬义,但是在软件编程中,这种思路确是一种解决问题最简单的算法,它通过一种类似于蛮干的思路,一步一步地往前走,每走一步都更靠近目标结果一些,直到遇到障碍物,我们才考虑往回走。然后再继续尝试向前。通过这样的波浪式前进方法,最终达到目的地。当然整个过程需要很多往返,这样的前进方式,效率比较低下。

2.适用范围

   适用于那些不存在简明的数学模型以阐明问题的本质,或者存在数学模型,但是难于实现的问题。

3.应用场景

   在8*8国际象棋棋盘上,要求在每一行放置一个皇后,且能做到在竖方向,斜方向都没有冲突。国际象棋的棋盘如下图所示:

3c3f32555ed870c1b745aeb2

4.分析

  基本思路如上面分析一致,我们采用逐步试探的方式,先从一个方向往前走,能进则进,不能进则退,尝试另外的路径。首先我们来分析一下国际象棋的规则,这些规则能够限制我们的前进,也就是我们前进途中的障碍物。一个皇后q(x,y)能被满足以下条件的皇后q(row,col)吃掉

1)x=row(在纵向不能有两个皇后)

2)  y=col(横向)

3)col + row = y+x;(斜向正方向)

4)  col - row = y-x;(斜向反方向)

遇到上述问题之一的时候,说明我们已经遇到了障碍,不能继续向前了。我们需要退回来,尝试其他路径。

我们将棋盘看作是一个8*8的数组,这样可以使用一种蛮干的思路去解决这个问题,这样我们就是在8*8=64个格子中取出8个的组合,C(64,80) = 4426165368,显然这个数非常大,在蛮干的基础上我们可以增加回溯,从第0列开始,我们逐列进行,从第0行到第7行找到一个不受任何已经现有皇后攻击的位置,而第五列,我们会发现找不到皇后的安全位置了,前面四列的摆放如下:

image

第五列的时候,摆放任何行都会上图所示已经存在的皇后的攻击,这时候我们认为我们撞了南墙了,是回头的时候了,我们后退一列,将原来摆放在第四列的皇后(3,4)拿走,从(3,4)这个位置开始,我们再第四列中寻找下一个安全位置为(7,4),再继续到第五列,发现第五列仍然没有安全位置,回溯到第四列,此时第四列也是一个死胡同了,我们再回溯到第三列,这样前进几步,回退一步,最终直到在第8列上找到一个安全位置(成功)或者第一列已经是死胡同,但是第8列仍然没有找到安全位置为止

总结一下,用回溯的方法解决8皇后问题的步骤为:

1)从第一列开始,为皇后找到安全位置,然后跳到下一列

2)如果在第n列出现死胡同,如果该列为第一列,棋局失败,否则后退到上一列,在进行回溯

3)如果在第8列上找到了安全位置,则棋局成功。

8个皇后都找到了安全位置代表棋局的成功,用一个长度为8的整数数组queenList代表成功摆放的8个皇后,数组索引代表棋盘的col向量,而数组的值为棋盘的row向

量,所以(row,col)的皇后可以表示为(queenList[col],col),如上图中的几个皇后可表示为:

queenList[0] = 0;  queenList[1] = 3;   queenList[2] = 1;  queenList[3] = 4;   queenList = 2;

我们看一下如何设计程序:

首先判断(row,col)是否是安全位置的算法:

  bool IsSafe(int col,int row,int[] queenList)
        
{
            
//只检查前面的列
            for (int tempCol = 0; tempCol < col; tempCol++)
            
{
                
int tempRow = queenList[tempCol];
                
if (tempRow == row)
                
{
                    
//同一行
                    return false;
                }

                
if (tempCol == col)
                
{
                    
//同一列
                    return false;
                }

                
if (tempRow - tempCol == row - col || tempRow + tempCol == row + col)
                
{
                    
return false;
                }

            }

            
return true;
        }

设定一个函数,用于查找col列后的皇后摆放方法:

/// <summary>
        
/// 在第col列寻找安全的row值
        
/// </summary>
        
/// <param name="queenList"></param>
        
/// <param name="col"></param>
        
/// <returns></returns>

        public bool PlaceQueue(int[] queenList, int col)
        
{
            
int row = 0;
            
bool foundSafePos = false;
            
if (col == 8//结束标志
            {
                
//当处理完第8列的完成
                foundSafePos = true;
            }

            
else
            
{
                
while (row < 8 && !foundSafePos)
                
{
                    
if (IsSafe(col, row, queenList))
                    
{
                        
//找到安全位置
                        queenList[col] = row;
                        
//找下一列的安全位置
                        foundSafePos = PlaceQueue(queenList, col + 1);
                        
if (!foundSafePos)
                        
{
                            row
++;
                        }

                    }

                    
else
                    
{
                        row
++;
                    }

                }

            }

            
return foundSafePos;
        }

调用方法:

 static void Main(string[] args)
        
{
            EightQueen eq 
= new EightQueen();
            
int[] queenList = new int[8];
            
for (int j = 0; j < 8; j++)
            
{
                Console.WriteLine(
"-----------------"+j+"---------------------");
                queenList[
0= j;
                
bool res = eq.PlaceQueue(queenList, 1);

                
if (res)
                
{
                    Console.Write(
"   ");       
                    
for (int i = 0; i < 8; i++)
                    
{
                        Console.Write(
" " + i.ToString() + " ");       
                    }

                    Console.WriteLine(
"");
                    
for (int i = 0; i < 8; i++)
                    
{
                        Console.Write(
" "+i.ToString()+" ");                       
                        
for (int a = 0; a < 8; a++)
                        
{                           
                            
if (i == queenList[a])
                            
{
                                Console.Write(
" q ");
                            }

                            
else
                            
{
                                Console.Write(
" * ");
                            }

                        }

                        Console.WriteLine(
"");
                                
                    }

                  
                    Console.WriteLine(
"---------------------------------------");
                }

                
else
                
{
                    Console.WriteLine(
"不能完成棋局,棋局失败!");
                }

            }

            Console.Read();
        }

递归算法PlaceQueue,完成这样的功能:它寻找第col列后的皇后的安全摆放位置,如果该函数返回了false,表示当前进入了死胡同,需要进行回溯,直到为0-7列都找

到了安全位置或者找遍这些列都找不到安全位置的时候终止。

用递归算法解决8皇后问题的示例程序:

/Files/jillzhang/EightQueens.rar

欢迎大家下载;

-----------------------------------------------------------------------------------------------------------------

递归算法到这篇为止,已经学习到了分而治之,动态编程,回溯等重要思想,也用这些问题解决了一些具体问题,比如排序,背包,8皇后问题等,通过对理论的学习

和对实际问题的解决,充分理解递归算法的使用方法。在编写学习系列的过程中,绝大多数都参考数据结构C++语言描述-应用标准模板库 ,特此感谢原书作者:

William Ford,William Topp,和译者陈军。

下一系列主要想通过6-8篇的篇幅来学习图论的基础知识。多谢大家支持



作者:jillzhang
出处:http://jillzhang.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted @ 2007-10-21 15:19 Robin Zhang 阅读(3558) 评论(9)  编辑 收藏 网摘 所属分类: 算法

  回复  引用  查看    
#1楼 2007-10-21 16:30 | 农夫三拳      
  回复  引用  查看    
#2楼 2007-11-05 17:20 | 专研.NET      
学习了
  回复  引用    
#3楼 2008-11-17 11:06 | 1特 [未注册用户]
你好象只能输出8组解,还有88组怎么办
  回复  引用    
#4楼 2008-12-17 22:33 | 冰封空间 [未注册用户]
三楼的兄弟,八皇后有92个解,不是96个,附上八皇后的JAVA算法:[含输入位置]

//8 Queen 递归算法
//如果有一个Q 为 chess[i]=j;
//则不安全的地方是 k行 j位置,j+k-i位置,j-k+i位置

class Queen8{

static final int QueenMax = 8;
static int oktimes = 0;
static int chess[] = new int[QueenMax];//每一个Queen的放置位置


public static void main(String[] args) {
long time = System.currentTimeMillis();
for (int i=0;i<QueenMax;i++)chess[i]=-1;
placequeen(0);
System.out.println("\n\n\n八皇后共有"+oktimes+"个解法 made by yifi 2003");
System.out.println((System.currentTimeMillis() - time) + "毫秒");
}


public static void placequeen(int num){ //num 为现在要放置的行数
int i=0;
boolean qsave[] = new boolean[QueenMax];
for(;i<QueenMax;i++) qsave[i]=true;

//下面先把安全位数组完成
i=0;//i 是现在要检查的数组值
while (i<num){
qsave[chess[i]]=false;
int k=num-i;
if ( (chess[i]+k >= 0) && (chess[i]+k < QueenMax) ) qsave[chess[i]+k]=false;
if ( (chess[i]-k >= 0) && (chess[i]-k < QueenMax) ) qsave[chess[i]-k]=false;
i++;
}
//下面历遍安全位
for(i=0;i<QueenMax;i++){
if (qsave[i]==false)continue;
if (num<QueenMax-1){
chess[num]=i;
placequeen(num+1);
}
else{ //num is last one
chess[num]=i;
oktimes++;
System.out.println("这是第"+oktimes+"个解法 如下:");
System.out.println("第n行: 1 2 3 4 5 6 7 8");

for (i=0;i<QueenMax;i++){
String row="第"+(i+1)+"行: ";
if (chess[i]==0);
else
for(int j=0;j<chess[i];j++) row+="--";
row+="++";
int j = chess[i];
while(j<QueenMax-1){row+="--";j++;}
System.out.println(row);
}
}
}
//历遍完成就停止
}
}




输出结果形式如下:
这是第1个解法 如下:
第n行: 1 2 3 4 5 6 7 8
第1行: ++--------------
第2行: --------++------
第3行: --------------++
第4行: ----------++----
第5行: ----++----------
第6行: ------------++--
第7行: --++------------
第8行: ------++--------

……

这是第92个解法 如下:
第n行: 1 2 3 4 5 6 7 8
第1行: --------------++
第2行: ------++--------
第3行: ++--------------
第4行: ----++----------
第5行: ----------++----
第6行: --++------------
第7行: ------------++--
第8行: --------++------

八皇后共有92个解法 made by yifi 2003
93毫秒

  回复  引用    
#5楼 2008-12-17 22:40 | 冰封空间 [未注册用户]
下面是我自己写过的一个八皇后,自认为是非常优化的了,也包含输出皇后的位置(因为没考虑输出的效率,嘿嘿,所以慢了些,当然八皇后的算法不在于输于,在于递归):

public class Queen_Java {

int QUEEN_COUNT = 8; //是多少皇后
static final int EMPTY = 0;
int[][] count = new int[QUEEN_COUNT][QUEEN_COUNT];
int[] QueenIndex = new int[QUEEN_COUNT];
int resultCount = 0;
long time = System.currentTimeMillis();

public void putQueenIndex(int row) {
for (int col = 0; col < QUEEN_COUNT; col++) {
if (count[row][col] == EMPTY) {
for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) {
count[iRow][col]++;
if ((col - iRow + row) >= 0) {
count[iRow][col - iRow + row]++;
}
if ((col + iRow - row) < QUEEN_COUNT) {
count[iRow][col + iRow - row]++;
}
}
QueenIndex[row] = col;
if (row == QUEEN_COUNT - 1) {
print(++resultCount);
} else {
putQueenIndex(row + 1);
}
for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) {
count[iRow][col]--;
if ((col - iRow + row) >= 0) {
count[iRow][col - iRow + row]--;
}
if ((col + iRow - row) < QUEEN_COUNT) {
count[iRow][col + iRow - row]--;
}
}
}
}
if (row == 0) {
System.out.println(QUEEN_COUNT + "皇后共有 " + resultCount + " 个解\n"
+ (System.currentTimeMillis() - time) + "毫秒");
}
}

public void print(int n) {
System.out.println(QUEEN_COUNT + "皇后的第 " + n + " 个解:");
for (int i = 0; i < QUEEN_COUNT; i++) {
for (int j = 0; j < QUEEN_COUNT; j++) {
System.out.print(QueenIndex[i] == j ? " * " : " - ");
}
System.out.println();
}
System.out.println();
}

public static void main(String[] args) {
new Queen_Java().putQueenIndex(0);
}
}

输出结果如下:

8皇后的第 1 个解:
* - - - - - - -
- - - - * - - -
- - - - - - - *
- - - - - * - -
- - * - - - - -
- - - - - - * -
- * - - - - - -
- - - * - - - -

……

8皇后的第 92 个解:
- - - - - - - *
- - - * - - - -
* - - - - - - -
- - * - - - - -
- - - - - * - -
- * - - - - - -
- - - - - - * -
- - - - * - - -

8皇后共有 92 个解
94毫秒

  回复  引用    
#6楼 2008-12-17 23:11 | 冰封空间 [未注册用户]
去掉输出,然后测了一下16个皇后的结果如下:
16皇后共有 14772512 个解
207640毫秒

public class Queen_Java_NoOut {

static final int QUEEN_COUNT = 16; //是多少皇后
static final int EMPTY = 0;
int[][] count = new int[QUEEN_COUNT][QUEEN_COUNT];
int[] QueenIndex = new int[QUEEN_COUNT];
int resultCount = 0;

public void putQueenIndex(int row) {
for (int col = 0; col < QUEEN_COUNT; col++) {
if (count[row][col] == EMPTY) {
for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) {
count[iRow][col]++;
if ((col - iRow + row) >= 0) {
count[iRow][col - iRow + row]++;
}
if ((col + iRow - row) < QUEEN_COUNT) {
count[iRow][col + iRow - row]++;
}
}
QueenIndex[row] = col;
if (row == QUEEN_COUNT - 1) {
++resultCount;
} else {
putQueenIndex(row + 1);
}
for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) {
count[iRow][col]--;
if ((col - iRow + row) >= 0) {
count[iRow][col - iRow + row]--;
}
if ((col + iRow - row) < QUEEN_COUNT) {
count[iRow][col + iRow - row]--;
}
}
}
}
}
public static void main(String[] args) {
Queen_Java_NoOut obj = new Queen_Java_NoOut();
long time = System.currentTimeMillis();
obj.putQueenIndex(0);
long useTime = System.currentTimeMillis() - time;
System.out.println(QUEEN_COUNT + "皇后共有 " + obj.resultCount + " 个解\n" + useTime + "毫秒");
}
}
  回复  引用    
#7楼 2008-12-17 23:24 | 冰封空间 [未注册用户]
如果还想加速只能用位运算,速度可能会变为原来的八分之一
  回复  引用    
#8楼 2008-12-17 23:32 | 冰封空间 [未注册用户]
最快的如下:

import java.util.Calendar;

public class Queen_Fastest {

public static int sum = 0, upperlimit = 1;

public static void compute(int row, int ld, int rd) {

if (row != upperlimit) {
int pos = upperlimit & ~(row | ld | rd);
while (pos != 0)
{
int p = pos & -pos;
pos -= p;
compute(row + p, (ld + p) << 1, (rd + p) >> 1);
}

} else
sum++;
}

public static void main(String[] args) {
Calendar start;
int n = 8;
if (args.length > 0)
n = Integer.parseInt(args[0]);
start = Calendar.getInstance();
if ((n < 1) || (n > 32)) {
System.out.println(" 只能计算1-32之间\n");
return;
}
System.out.println(n + " 皇后\n");
upperlimit = (upperlimit << n) - 1;
compute(0, 0, 0);
System.out.println("共有" + sum + "种排列, 计算时间"
+ (Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis()) / 1000 + "秒 \n");
}

}

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
Google站内搜索
[推荐职位]上海盛大网络招聘架构师



China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!
开发者征途系统新作:《设计模式——基于C#的工程化实现及扩展》

相关文章:

相关链接: