• 面试经典之剑指offer58八皇后问题


    问题描述:在国际象棋中,皇后的属性是在不能在同一行,也不能在同一列,也不能在统一斜线上,否则就要被拼掉,最经典的八皇后问题是给你一个8*8的棋盘和8个皇后,求出所有可能排列的方式,一般不考虑拓扑相似性。

    解答方案:何海涛博客中给出的方案是先确定解空间(这么做是因为能够确定解空间的大小),然后对每一个可能的解进行检查,如果满足就输出,他的思路是既然皇后不能在一行,那么对于8皇后,每个皇后我们只需要确定他们在各自行的位置就好了,位置当然只能是1,2…,8,所以解空间可以缩小到1到8的全排列。然后进行检查。

    问题是这样的效率比较低,当然,回溯法剪枝可以大幅减少八皇后问题的解空间探索个数,这个思路没什么新意,我权当练手写了出来,记录一下,代码如下:

    #include <iostream>
    
    #include <vector>
    
    using namespace std;
    
    const int k=8;
    
    int count=0;
    
    void PutQueen(int row,vector<int> & loc);
    
    bool checkIsValid(int curRow,int curLoc,vector<int> &loc_prev);
    
    int main()
    
    {
    
    	vector<int> loc;
    
    	PutQueen(0,loc);
    
    	cout<<"There is "<<count<<" kind of location";
    
    	getchar();
    
    }
    
    void PutQueen(int row,vector<int> & loc)
    
    {
    
    	
    
    	if(loc.size()==k)
    
    	{
    
    		vector<int>::iterator iter;
    
    		for(iter=loc.begin();iter!=loc.end();++iter)
    
    		{
    
    			cout<<*iter;
    
    		}
    
    		cout<<endl;
    
    		count++;
    
    		return;
    
    	}
    
    	if(row>=k)return;
    
    	for( int col=0;col<k;++col)
    
    	{
    
    		if(checkIsValid(row,col,loc))
    
    		{
    
    			loc.push_back(col);
    
    			PutQueen(row+1,loc);
    
    			loc.pop_back();
    
    		}
    
    	}
    
    	return;
    
    }
    
    bool checkIsValid(int curRow,int curLoc,vector<int> &loc_prev)
    
    {
    
    	if(curRow<1)return true;
    
    	else
    
    	{
    
    		for(int r=0;r<curRow;++r)
    
    		{
    
    			if(loc_prev[r]==curLoc||(curLoc-loc_prev[r])==(r-curRow)||(curLoc-loc_prev[r])==(curRow-r))
    
    			return false;
    
    		}
    
    		return true;
    
    	}
    
    }
  • 相关阅读:
    单播、广播和多播IP地址
    nagios安装部署及详细配置说明(转)
    centos6.5下cacti部署说明
    HAproxy配置详解
    mysql全量和增量备份详解(带脚本)
    lvs原理及安装部署详解(参考)
    curl命令的用法
    mysql日志解析
    MySQL查看和修改表的存储引擎
    mysql备份和还原
  • 原文地址:https://www.cnblogs.com/obama/p/3026424.html
Copyright © 2020-2023  润新知