資源簡介
人工只能作業,利用python實現深度優先搜索解決八數碼問題,測試通過,
代碼片段和文件信息
“““
深度優先搜索解決八數碼問題
“““
GOAL?=?‘‘‘1-2-3
8-e-4
7-6-5‘‘‘
INITIAL?=?‘‘‘1-e-3
7-2-4
6-8-5‘‘‘
#?INITIAL?=?‘‘‘2-8-3
#?1-6-4
#?7-e-5‘‘‘
#?將狀態字符串轉化為列表
def?string_to_list(input_string):
????return?[x.split(‘-‘)?for?x?in?input_string.split(‘\n‘)]
#?將狀態列表轉化為字符串
def?list_to_string(input_list):
????return?‘\n‘.join([‘-‘.join(x)?for?x?in?input_list])
#?獲取e的坐標
def?get_location(rows?input_element):
????for?i?row?in?enumerate(rows):
????????for?j?item?in?enumerate(row):
????????????if?item?==?input_element:
????????????????return?i?j
#?找空格的左、上、右、下四個位置的元素
def?get_actions(cur_state):
????rows?=?string_to_list(cur_state)
????row_empty?col_empty?=?get_location(rows?‘e‘)
????actions?=?[]
????if?col_empty?>?0:??#?可左移
????????actions.append(rows[row_empty][col_empty?-?1])
????if?row_empty?>?0:??#?可上移
????????actions.append(rows[row_empty?-?1][col_empty])
????if?col_empty?2:??#?可右移
????????actions.append(rows[row_empty][col_empty?+?1])
????if?row_empty?2:??#?可下移
????????actions.append(rows[row_empty?+?1][col_empty])
????return?actions
#?移動一個數字返回移動成功后的狀態字符串及其父狀態
def?get_result(state?action):
????rows?=?string_to_list(state)
????row_empty?col_empty?=?get_location(rows?‘e‘)??#?獲得當前狀態中的空格的坐標值
????row_new?col_new?=?get_location(rows?action)
????##交換空格和數字的位置
????rows[row_empty][col_empty]?rows[row_new][col_new]?=?rows[row_new][col_new]?rows[row_empty][col_empty]
????return?list_to_string(rows)?state?action
#?是否到達目標狀態
def?is_
- 上一篇:人工魚群算法求函數的最大值
- 下一篇:寬度優先算法
評論
共有 條評論