資源簡介
人工智能作業,利用python實現寬度優先BFS搜索解決八數碼問題
代碼片段和文件信息
“““
寬度優先搜索解決八數碼問題
上機要求:
(1)在此代碼基礎上完成深度優先搜索和A*搜索,并顯示結果。當場驗收。
(2)完成上機報告
“““
GOAL?=?‘‘‘1-2-3
8-e-4
7-6-5‘‘‘
INITIAL?=?‘‘‘1-e-3
7-2-4
6-8-5‘‘‘
#?將狀態字符串轉化為列表
def?string_to_list(input_string):
????return?[x.split(‘-‘)?for?x?in?input_string.split(‘\n‘)]
##print(string_to_list(INITIAL))
####———————————————————————————
####?[[‘1‘?‘e‘?‘2‘]?[‘6‘?‘3‘?‘4‘]?[‘7‘?‘5‘?‘8‘]]
####———————————————————————————
#?將狀態列表轉化為字符串
def?list_to_string(input_list):
????return?‘\n‘.join([‘-‘.join(x)?for?x?in?input_list])
##print(list_to_string([[‘1‘?‘e‘?‘2‘]?[‘6‘?‘3‘?‘4‘]?[‘7‘?‘5‘?‘8‘]]))
####——————
####?1-e-2
####?6-3-4
####?7-5-8
####——————
#?獲取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
##print(get_location([[‘1‘?‘e‘?‘2‘]?[‘6‘?‘3‘?‘4‘]?[‘7‘?‘5‘?‘8‘]]‘e‘))
####——————
####?(0?1)
####——————
#?找空格的左、上、右、下四個位置的元素
def?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:??#?可下稱
????
- 上一篇:深度優先搜索解決八數碼問題
- 下一篇:A*算法解決八數碼問題
評論
共有 條評論