数据结构---八皇后问题

算法思想:利用行号固定,列号全排列解决;这样没有i == j 和board[i] == board[j]的冲突;
 只要检测(j-i) == (size_t)abs(board[i]-board[j])就说明冲突!
 1    #include <cmath>
 2    #include <iostream>
 3    #include <vector>
 4    #include <algorithm>
 5   
 6    using namespace std;
 7    const int MAX = 8;
 8   
 9    vector<int> board(MAX);
10   
11    void show_result()
12    {
13        for(size_t i = 0; i < board.size(); i++)
14            cout<<"("<<i<<","<<board[i]<<")";
15        cout<<endl;
16    }
17   
18    int check_cross()
19    {
20        for(size_t i = 0; i < board.size()-1; i++)
21        {
22            for(size_t j = i+1; j < board.size(); j++)
23            {
24                if((j-i) == (size_t)abs(board[i]-board[j]))
25                    return 1;
26            }
27        }
28        return 0;
29    }
30   
31    void put_chess()
32    {
33        while(next_permutation(board.begin(), board.end()))
34        {
35            if(!check_cross())
36            {
37                show_result();
38            }
39        }
40    }
41   
42    int main()
43    {
44        for(size_t i =0; i < board.size(); i++)
45            board[i] = i;
46        put_chess();
47        return 0;
48    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值