python迷宮求解 從Python迷宮裡找到路

2021-10-12 10:49:52 字數 2457 閱讀 3428

如果您正在尋找最短路徑,我建議您:

將迷宮轉換為具有以下屬性的加權圖:頂點集是所有可通過正方形的集合。

邊集是相鄰可通過正方形的所有元組的集合。

每個邊的權重為1。

在這之後,讓迪克斯特拉先生或a*為你做這項工作。在

我能找到的最短路徑是「ssssseeeseeeess」。在

這裡是我發現它的快速且骯髒的**:#! /usr/bin/python3

lab = [[1,1,1,1,1,1,1,1,1,1,1,1],[1,0,0,0,0,0,0,0,0,0,0,1],[1,0,1,1,1,1,1,1,0,1,1,1],[1,0,1,0,0,0,0,0,0,0,0,1],[1,0,1,0,1,1,1,1,1,1,0,1],[1,0,1,0,1,0,0,0,0,0,0,1],[1,0,0,0,1,1,0,1,1,1,0,1],[1,0,1,0,0,0,0,1,0,1,1,1],[1,0,1,1,0,1,0,0,0,0,0,1],[1,0,1,0,0,1,1,1,1,1,0,1],[1,0,0,0,1,1,0,0,0,0,0,1],[1,1,1,1,1,1,1,1,1,1,1,1]]

class node:

def __init__ (self, x, y):

self.x = x

self.y = y

self.neighbours = [ (x + xoff, y + yoff) for xoff, yoff in

( (1, 0), (0, 1), (0, -1), (-1, 0) )

if not lab [y + yoff] [x + xoff] ]

self.distance = ...

self.path = ...

self.visited = false

def __repr__ (self):

return '{}: ({})'.format ( (self.x, self.y), self.neighbours)

nodes = {}

for y in range (12):

for x in range (12):

if lab [y] [x]: continue

nodes [x, y] = node (x, y)

current = nodes [1, 1]

current.distance = 0

current.path =

unvisited = set (nodes.keys () )

while true:

dist = current.distance + 1

for nx, ny in current.neighbours:

if (nx, ny) not in unvisited: continue

neighbour = nodes [nx, ny]

if neighbour.distance is ... or neighbour.distance > dist:

neighbour.distance = dist

neighbour.path = current.path + [ (current.x, current.y) ]

current.visited = true

unvisited.remove ( (current.x, current.y) )

if not unvisited: break

current = sorted ( [node for node in nodes.values ()

if not node.visited and node.distance is not ...],

key = lambda node: node.distance) [0]

print (nodes [10, 10].path)

path = nodes [10, 10].path + [ (10, 10) ]

for (ax, ay), (bx, by) in zip (path, path [1:] ):

if ax == bx and ay > by: print ('n', end = '')

if ax == bx and ay < by: print ('s', end = '')

if ay == by and ax > bx: print ('w', end = '')

if ay == by and ax < bx: print ('e', end = '')

print ()

結果是:

^$或者,如果從右上角開始,結果是:[(10, 1), (9, 1), (8, 1), (8, 2), (8, 3), (9, 3), (10, 3), (10, 4), (10, 5), (9, 5), (8, 5), (7, 5), (6, 5), (6, 6), (6, 7), (6, 8), (7, 8), (8, 8), (9, 8), (10, 8), (10, 9)]

wwsseesswwwwssseeeess

AI 隨機迷宮 迷宮求解

本文記錄了,人工智慧中簡單的搜尋策略中的路徑搜尋策略中的a 演算法,來實現迷宮尋路的問題.這只是一次本人的課外作業 完整的程式原始碼已經傳送到我的git.這裡只記錄了我的思路和感想以及收穫.產生隨機迷宮 迷宮求解沒有迷宮怎麼可以呢.而本人是個懶人,每次都要手動輸入迷宮,重複性的工作讓我很不爽.你可以...

迷宮求解 窮舉求解法

迷宮求解是乙個理解資料結構中棧的比較好的實踐例子,下面進行分析 設迷宮是又乙個2維陣列組成的,元素只有0或1來表示是否通路,0代表通路,1代表有牆壁不通路 例如下圖中是一條通路 窮舉法 從入口出發,順某方向向前探索,如能走通,則繼續往前走,否則沿原路返回,換乙個方向再試,直到所有可能的銅鑼都探索到為...

A 演算法求解迷宮

cpp view plaincopy include include include using namespace std 方向向量 int direc 4 2 封閉,開放列表標記 enum flag 最小堆節點類 堆優先順序為 f g h g為當前的路徑長 h為估計當前位置到目標位置開銷探測 當...