Python实现经典算法八皇后问题

在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问一共有多少种摆法。

分别用递归回溯算法与遗传算法实现,代码如下

递归回溯解八皇后问题

import numpy

def findQueen(column):

    if column > 7:
        global count
        count+=1
        print(matrix)
        return
    else:
        for row in range(8):
            if check(row,column):
                matrix[row][column]=1
                arr[column]=row
                findQueen(column+1)
                matrix[row][column]=0
                arr[column]=0

def check(row,column):
    for k in range(len(arr)):
        if k >= column:
            return True
        if arr[k] == row or abs(arr[k] - row) == abs(k - column):
            return False

if __name__ == '__main__':
    count = 0
    matrix = numpy.zeros((8,8),dtype=int)
    arr = numpy.zeros(8,dtype=int)
    findQueen(0)
    print(count)

遗传算法解八皇后问题

import copy
import random
import math

种群大小
population_size = 8
父种群的编码列表
parent = []
子种群的编码列表
children = []
父种群每个个体的适应度
parent_fitness = []
子种群每个个体的适应度
children_fitness = []

初始化个体
def initial_individual():
    # 个体的编码
    individual = []
    # 8个编码
    for i in range(8):
        a = random.randint(0, 7)
        individual.append(a)
    # 计算生成的个体的适应度
    fit_score = update_fitness_score(individual)
    # 加入到种群中

    parent_fitness.append(fit_score)
    parent.append(individual)
    return

更新适应度函数
def update_fitness_score(individual):
    value = 0
    for i in range(8):
        for j in range(i + 1, 8):
            if individual[i] != individual[j]:
                x = j - i
                y = abs(individual[i] - individual[j])
                if x != y:
                    value += 1
    return value

初始化1个种群,种群大小为population_size
def initial_population():
    for i in range(population_size):
        initial_individual()
    return

选择出一个父本
def select():
    # 所有个体的适应度之和
    total_score = 0
    for fit in parent_fitness:
        total_score += fit

    # 轮盘赌中的数
    num = random.randint(0, total_score)
    # 前面的适应度之和
    front_score = 0
    for i in range(population_size):
        front_score += parent_fitness[i]
        # 如果此时前面的适应度之和大于生成的随机数,那么该数必定落在编号为 i 的个体上
        if front_score >= num:
            return i

变异
def mutation(change_individual):
    # 第pos个基因发生变异
    pos = random.randint(0, 7)
    # 改变的值
    change = random.randint(0, 7)
    change_individual[pos] = change
    return change_individual

交叉产生后代
def hybridization():
    # 选择两个父本
    first = select()
    second = select()
    selected_parents = copy.deepcopy([parent[first], parent[second]])
    # 交换从pos1到pos2的基因
    pos1 = random.randint(0, 6)
    pos2 = random.randint(0, 6)
    # 保证pos1  pos2:
        pos1, pos2 = pos2, pos1
    # 交叉
    tmp = selected_parents[0][pos1:pos2]
    selected_parents[0][pos1:pos2] = selected_parents[1][pos1:pos2]
    selected_parents[1][pos1:pos2] = tmp
    # 一定的概率发生变异,假设概率为0.5
    may = random.random()
    if may > 0.5:
        selected_parents[0] = mutation(selected_parents[0])
    may = random.random()
    if may > 0.5:
        selected_parents[1] = mutation(selected_parents[1])
    # 更新适应度
    first_fit = update_fitness_score(selected_parents[0])
    second_fit = update_fitness_score(selected_parents[1])

    # 加入到子代中
    children.append(selected_parents[0])
    children.append(selected_parents[1])
    children_fitness.append(first_fit)
    children_fitness.append(second_fit)
    return

初始化种群
initial_population()
计算迭代次数
count = 0
not a number
find = float('nan')
while True:
    count += 1
    if count % 1000 == 0:
        print('第%d' % count + '次迭代')
    # 杂交population_size/2次产生population_size个后代
    for k in range(population_size // 2):
        hybridization()
    # 如果某个个体适应度达到28,说明此时找到了一个解
    for k in range(population_size):
        if children_fitness[k] == 28:
            # 记录解的位置
            find = k
            break
    if not math.isnan(find):
        break
    # 将子代种群放入父代中作为新的父代,子代清空
    parent[0:population_size] = children[0:population_size]
    parent_fitness[0:population_size] = children_fitness[0:population_size]
    children = []
    children_fitness = []

此时找到满足要求的子代个体
res = children[find]
print(res)

构造棋盘
res_queen = [[0 for i in range(8)] for j in range(8)]
for t in range(8):
    res_queen[res[t]][t] = 1
将棋盘打印
print("找到结果:")
for t in range(8):
    print(res_queen[t])

Original: https://www.cnblogs.com/left23333/p/16347767.html
Author: Left23333
Title: Python实现经典算法八皇后问题

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/582412/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 用华为云cli(命令行程序),管理华为云服务器的,安全组端口

    关键字 hcloud 华为 命令行 linux windows powershell 前些天,大家因为华为云,是否应该默认开启端口,大家吵起来了,所以我抽空写了此文。解决问题,缓解…

    Linux 2023年6月14日
    087
  • linux内核源代码组织结构

    linux版本 linux 3.6.24 第一个数字主版本号 第二个数字是偶数代表是稳定版 第三个代表修订次数 Original: https://www.cnblogs.com/…

    Linux 2023年6月7日
    0101
  • 【Example】C++运算符重载

    首先,阅读之前要先搞清楚什么是运算符、函数重载。函数重载就是在一个范围内为一个函数声明多个实现方式,函数名必须一致。 那么C++运算符是否可以重载呢?可以!先弄清什么时候需要进行运…

    Linux 2023年6月13日
    0108
  • wsl2安装百度apollo及其基本配置

    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart dism….

    Linux 2023年6月7日
    0102
  • OpenSSL测试-随机数

    任务详情 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务 使用OpenSSL定义一个私有函数 static int getRandom(char…

    Linux 2023年6月8日
    098
  • 一文让你明白Redis持久化

    网上虽然已经有很多类似的介绍了,但我还是自己总结归纳了一下,自认为内容和细节都是比较齐全的。 文章篇幅有 4k 多字,货有点干,断断续续写了好几天,希望对大家有帮助。不出意外地话,…

    Linux 2023年5月28日
    089
  • python学习

    目录: 1、课程推荐以及书籍推荐 2、学习记录 2.1:无 1. 实践过程 廖雪峰的官方网站 2. 学习记录 2.1 无: posted @2022-02-12 19:44 风御之…

    Linux 2023年6月13日
    096
  • C盘空间怎么不够了?原来杀毒软件隔离区太大了

    打开小红伞的隔离区,文件全选,删除,居然一下多出20个G. C盘空间怎么不够了?原来杀毒软件隔离区太大了 麻了。打开小红伞的隔离区,文件全选,删除,一下多出20个G. 还有一个比较…

    Linux 2023年6月6日
    0113
  • Ubuntu14.04.5升级openssh8.0p1版本

    一、前言客户请广电公司扫描服务器漏洞,扫到阿里云服务器的OpenSSH_6.6.1p1版本存在如下高危漏洞,基于安全的考量,升级到8.0版本。1.OpenSSH安全绕过漏洞2.Op…

    Linux 2023年6月8日
    088
  • JS 模块化- 05 ES Module & 4 大规范总结

    1 ES Module 规范 ES Module 是目前使用较多的模块化规范,在 Vue、React 中大量使用,大家应该非常熟悉。TypeScript 中的模块化与 ES 类似。…

    Linux 2023年6月6日
    0124
  • docker 安装redis

    1、获取 redis 镜像 2、查看本地镜像 bind 127.0.0.1 #注释掉这部分,这是限制redis只能本地访问 protected-mode no #默认yes,开启保…

    Linux 2023年5月28日
    089
  • Windows针对子目录共享权限控制

    Windows的共享文件设置有两种,一种是共享这一个目录然后里面的子文件,文件夹权限则集成;一种是共享这个目录后,里面的子文件与文件夹权限可单独控制。 共享一 image-2021…

    Linux 2023年6月8日
    095
  • 前端基础之JavaScript(二)

    一、函数 1.1 函数定义 JavaScript中的函数和Python中的非常相似,只是定义方式有点区别。 // 普通函数定义 function f1() { console.lo…

    Linux 2023年6月14日
    095
  • springboot JDBC整合

    1、建立一个springboot项目,并导包:JDBC API 与 MySQL Driver 2、项目建好之后,发现自动帮我们导入了如下的启动器: <dependency&g…

    Linux 2023年6月14日
    0118
  • Linux虚拟机上按安装jdk1.8.0

    Linux虚拟机上按安装jdk1.8.0 1.准备工作 jdk1.8.0下载地址: http://www.oracle.com/technetwork/java/javase/do…

    Linux 2023年6月11日
    083
  • python获取Windows硬件特征信息

    1.python pip安装WMI 并用pyinstaller编译出device_chk.exe 参考内容:https://blog.csdn.net/fengmm521/arti…

    Linux 2023年6月7日
    088
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球