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)

大家都在看

  • Java基础系列–03_Java中的方法描述

    Java的方法(函数)的描述 方法(1)方法的定义:就是完成特定功能的代码块。注意:在很多语言里面有函数的定义,而在Java中,函数被称为方法。(2)格式:修饰符 返回值类型 方法…

    Linux 2023年6月7日
    0148
  • gcc/g++与动静库以及gdb

    gcc/g++ 程序转换为二进制 总共需要经过4个大步骤:1.预处理,2.编译,3.汇编,4.链接。 想要更深刻的了解它,可以通过Linux去深刻的了解他们。 先创建.C文件 并且…

    Linux 2023年6月13日
    0132
  • 以STM32和FPGA为核心的多组件协调工作系统

    posted @2019-06-09 22:04 xutopia 阅读(709 ) 评论() 编辑 Original: https://www.cnblogs.com/xutopi…

    Linux 2023年6月14日
    0165
  • redis如何设置密码

    密码设置这里简单介绍一下redis如何设置密码redis密码设置有两种方式,一种需要重启redis服务,一种不需要重启redis服务。 首先,介绍一下需要重启redis服务的设置方…

    Linux 2023年5月28日
    0131
  • 上篇:34个JavaScript栗子,从易到难。

    alert("hello world") document.write("hello world") console.log("好…

    Linux 2023年6月7日
    0120
  • 关于NLog在.NET CORE下如何进行日志的持久化及通过邮件发送日志

    配置过程 安装NLog 通过Nuget进行集成(NuGet Gallery | NLog.Web.AspNetCore 4.14.0) 通过命令行安装 Install-Packag…

    Linux 2023年6月14日
    0121
  • WPF 修复 ContextMenu 在开启 PerMonitorV2 后所用 DPI 错误

    本文告诉大家如何修复 WPF 的 ContextMenu 在开启 PerMonitorV2 之后,在双屏不同的 DPI 的设备上,在副屏弹出的 ContextMenu 使用了主屏的…

    Linux 2023年6月6日
    0127
  • GCC 内联汇编基础

    GCC 内联汇编 在 MIT6.828的实验中,有几处用到了很底层的函数,都以内联汇编的形式存在,例如 static inline uint32_t read_esp(void) …

    Linux 2023年6月8日
    0117
  • webshell 免杀

    https://xz.aliyun.com/t/11391 Original: https://www.cnblogs.com/cute/p/16356651.htmlAuthor…

    Linux 2023年5月28日
    0144
  • rsync

    Rsync-远程同步 简介 rsync是linux系统下的数据镜像备份工具。使用快速增量备份工具Remote Sync可以远程同步,支持本地复制,或者与其他SSH、rsync主机同…

    Linux 2023年6月13日
    0113
  • docker 容器大小查看及清理docker磁盘空间

    这篇文章最初是由博主创作的。请注明转载的来源: [En] This article is originally created by the blogger. Please ind…

    Linux 2023年5月27日
    0135
  • bash 教程-4 shell 脚本 调试 环境 [MD]

    我的GitHub 我的博客 我的微信 我的邮箱 bqt20094 baiqiantao@sina.com 脚本基础 脚本 script 就是包含一系列命令的一个文本文件,所有能够在…

    Linux 2023年5月28日
    0127
  • 快速上手FastJSON

    作为一名后端开发而言肯定会接触数据,把数据提供给前端或者把数据存储起来,目前比较火热的传输格式是json,给前端传json是再常见不过啦,甚至是往db里面直接存入json。 在ja…

    Linux 2023年6月14日
    0112
  • 文件批量改名(有规律)

    1.如你的文件放在桌面名字为file的文件内,我要把这些文件批量名称改为page1.jpg,page2.jpg,page3.jpg………. 2….

    Linux 2023年6月13日
    0119
  • [云原生]Kubernetes-集群搭建(第2章)

    一、前置知识点 二、kubeadm部署方式介绍 三、安装要求 四、最终目标 五、准备环境 六、环境初始化 6.1 设置系统主机名以及Hosts文件的相互解析 6.2 安装依赖文件(…

    Linux 2023年6月13日
    0113
  • Apache Shiro 身份验证绕过漏洞 (CVE-2020-1957)

    一、漏洞描述 Apache Shiro 是一个功能强大且易于使用的 Java 安全框架,它执行身份验证、授权、加密和会话管理。 在具有 Spring 动态控制器的 1.5.2 之前…

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