遗传算法求解迷宫寻宝藏问题,代码
时间: 2023-09-11 11:10:49 浏览: 51
好的,以下是一个简单的遗传算法求解迷宫寻宝藏问题的Python代码:
```python
import random
# 迷宫地图
maze = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
# 起点和终点
start_pos = (1, 1)
end_pos = (9, 8)
# 移动操作
moves = ['up', 'down', 'left', 'right']
# 遗传算法参数
POPULATION_SIZE = 50
GENERATIONS = 100
MUTATION_RATE = 0.1
# 生成随机个体
def generate_individual():
return [random.choice(moves) for _ in range(100)]
# 计算适应度
def calculate_fitness(individual):
x, y = start_pos
for move in individual:
if move == 'up':
y -= 1
elif move == 'down':
y += 1
elif move == 'left':
x -= 1
elif move == 'right':
x += 1
if (x, y) == end_pos:
return 1
if maze[y][x] == 1:
return 0
return 0
# 选择操作
def selection(population):
fitnesses = [calculate_fitness(individual) for individual in population]
total_fitness = sum(fitnesses)
probabilities = [fitness / total_fitness for fitness in fitnesses]
return random.choices(population, weights=probabilities, k=2)
# 交叉操作
def crossover(parents):
crossover_point = random.randrange(len(parents[0]))
child1 = parents[0][:crossover_point] + parents[1][crossover_point:]
child2 = parents[1][:crossover_point] + parents[0][crossover_point:]
return child1, child2
# 变异操作
def mutation(individual):
for i in range(len(individual)):
if random.random() < MUTATION_RATE:
individual[i] = random.choice(moves)
return individual
# 遗传算法主函数
def genetic_algorithm():
population = [generate_individual() for _ in range(POPULATION_SIZE)]
for generation in range(GENERATIONS):
new_population = []
for _ in range(POPULATION_SIZE // 2):
parents = selection(population)
child1, child2 = crossover(parents)
child1 = mutation(child1)
child2 = mutation(child2)
new_population.append(child1)
new_population.append(child2)
population = new_population
best_individual = max(population, key=calculate_fitness)
print('Generation:', generation, 'Best individual:', best_individual, 'Fitness:', calculate_fitness(best_individual))
# 运行遗传算法
genetic_algorithm()
```
代码说明:
1. 首先定义了迷宫地图、起点和终点、移动操作等必要的变量。
2. 然后定义了几个遗传算法的基本操作函数,包括生成随机个体、计算适应度、选择、交叉、变异等。
3. 最后定义了遗传算法主函数,其中首先生成初始种群,然后进行多代进化,每一代都进行选择、交叉、变异等操作,最后输出每一代的最佳个体和适应度。
4. 运行遗传算法函数即可得到寻宝的最优路径。