簡體   English   中英

使用BFS DFS解決8個難題問題(使用Python。需要一些建議)

[英]solving 8 puzzle problem with BFS DFS (Using Python. Needs some suggestion)

我的最終狀態是

0 1 2
3 4 5
6 7 8

我的圖看起來像這樣

graph = {0 :[1, 3],
         1 :[0, 4, 2],
         2 :[1, 5],
         3 :[0, 4, 6],
         4 :[1, 3, 5, 7],
         5 :[2, 4, 8],
         6 :[3, 7],
         7 :[4, 6, 8],
         8 :[5 ,7]
        }

1-我想知道是否應該嘗試其他方法,例如列表,是否有除graph(above)之外的其他語句。
2-圖形有問題嗎?
給出的問題-

例子[1,5,3,2,0,4,7,8,6] <-更像這樣
1 5 3
2 0 4
7 8 6

我應該找到給定狀態的最終狀態

謝謝

因此,有4種極端情況:

  • 第一排
  • 底行
  • 最左欄
  • 最右欄

(和組合)

我們可以像這樣輕松地處理它們:

data = [1, 5, 3,
        2, 0, 4,
        7, 8, 6]

width = 3
height = 3

graph = {number: list() for number in data}

for idx, number in enumerate(data):
    current_height = int(idx / width)
    current_width = idx % width

    if current_width != width - 1:  # if next element in same row
        graph[number].append(data[idx + 1])

    if current_width != 0:  # if prev element in same row
        graph[number].append(data[idx - 1])

    if current_height != 0:  # if there is top element
        graph[number].append(data[idx - 3])

    if current_height != height - 1:  # if there is bottom element
        graph[number].append(data[idx + 3])

import pprint
pprint.pprint(graph)

這段代碼將構造圖形,但是這全是為了解決這個難題嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM