1. 程式人生 > >A*(A星)演算法python實現

A*(A星)演算法python實現

在春節放假前兩天我偶然看到了A*演算法,感覺挺有意思。正好放假前也沒有什麼事情,就花了一個下午寫出演算法的骨架,節後又花了半天時間完善螢幕輸出的細節並且除錯完成。
該實現只是一時興起的隨手而作,沒有考慮效能和擴充套件性等問題。正在學習A*的朋友可以拿去隨便折騰。
Email: [email protected]

程式碼的執行效果如下:
這裡寫圖片描述

#!/usr/bin/python​
# vim:set fileencoding=utf-8

# 在春節放假前兩天我偶然看到了A*演算法,感覺挺有意思。正好放假前
# 也沒有什麼事情,就花了一個下午寫出演算法的骨架,節後又花了半天
# 時間完善螢幕輸出的細節並且除錯完成。 # 該實現只是一時興起的隨手而作,沒有考慮效能和擴充套件性等問題。正 # 在學習A*的朋友可以拿去隨便折騰。 # email: [email protected] import sys _2dmap = [] start = None end = None open_list = {} close_list = {} map_border = () class Node: def __init__(this, father, x, y): if
x < 0 or x >= map_border[0] or y < 0 or y >= map_border[1]: raise Exception("node position can't beyond the border!") this.father = father this.x = x this.y = y if father != None: G2father = calc_G(father, this) if not G2father: raise
Exception("father is not valid!") this.G = G2father + father.G this.H = calc_H(this, end) this.F = this.G + this.H else: this.G = 0 this.H = 0 this.F = 0 def reset_father(this, father, new_G): if father != None: this.G = new_G this.F = this.G + this.H this.father = father def calc_G(node1, node2): x1 = abs(node1.x-node2.x) y1 = abs(node1.y-node2.y) if (x1== 1 and y1 == 0): return 10 # same row if (x1== 0 and y1 == 1): return 10 # same col if (x1== 1 and y1 == 1): return 14 # cross else: return 0 def calc_H(cur, end): return abs(end.x-cur.x) + abs(end.y-cur.y) # NOTE 這個地方可能成為效能瓶頸 def min_F_node(): if len(open_list) == 0: raise Exception("not exist path!") _min = 9999999999999999 _k = (start.x, start.y) for k,v in open_list.items(): if _min > v.F: _min = v.F _k = k return open_list[_k] # 把相鄰節點加入open list, 如果發現終點說明找到了路徑 def addAdjacentIntoOpen(node): # 將該節點從開放列表移到關閉列表當中。 open_list.pop((node.x, node.y)) close_list[(node.x, node.y)] = node _adjacent = [] # 相鄰節點要注意邊界的情況 try: _adjacent.append(Node(node , node.x - 1 , node.y - 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x , node.y - 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x + 1 , node.y - 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x + 1 , node.y)) except Exception,e: pass try: _adjacent.append(Node(node , node.x + 1 , node.y + 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x , node.y + 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x - 1 , node.y + 1)) except Exception,e: pass try: _adjacent.append(Node(node , node.x - 1 , node.y)) except Exception,e: pass for a in _adjacent: if (a.x,a.y) == (end.x, end.y): new_G = calc_G(a, node) + node.G end.reset_father(node, new_G) print "find path finish!" return True if (a.x,a.y) in close_list: continue if (a.x,a.y) not in open_list: open_list[(a.x,a.y)] = a else: exist_node = open_list[(a.x,a.y)] new_G = calc_G(a, node) + node.G if new_G < exist_node.G: exist_node.reset_father(node, new_G) return False def find_the_path(start, end): open_list[(start.x, start.y)] = start the_node = start try: while not addAdjacentIntoOpen(the_node): the_node = min_F_node() except Exception,e: # path not exist print e return False return True #======================================================================= def print_map(): print ' Y', for i in xrange(len(_2dmap)): print i, print print ' X' row = 0 for l in _2dmap: print '%3d'%row,' ', row = row+1 for i in l: print i, print def mark_path(node): if node.father == None: return _2dmap[node.x][node.y] = '#' mark_path(node.father) def preset_map(): global start,end,map_border _2dmap.append('S X . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. X . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. X . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . . . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X X X X .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X X X'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . . . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . .'.split()) _2dmap.append('. . . . . . . . . . . . . . . X . X . E'.split()) map_border = (len(_2dmap),len(_2dmap[0])) row_index = 0 for row in _2dmap: col_index = 0 for n in row: if n == 'X': block_node = Node(None, row_index, col_index) close_list[(block_node.x, block_node.y)] = block_node elif n == 'S': start = Node(None, row_index, col_index) elif n == 'E': end = Node(None, row_index, col_index) col_index = col_index + 1 row_index = row_index + 1 if __name__=='__main__': if len(sys.argv) < 3: preset_map() else: x = int(sys.argv[1]) y = int(sys.argv[2]) map_border = (x,y) _start = raw_input('pls input start point:') _end = raw_input('pls input end point:') _start = _start.split(',') _end = _end.split(',') _start = (int(_start[0]), int(_start[1])) _end = (int(_end[0]), int(_end[1])) start = Node(None, _start[0], _start[1]) end = Node(None, _end[0], _end[1]) # gen map _2dmap = [['.' for i in xrange(y)] for i in xrange(x) ] # put start and end _2dmap[_start[0]][_start[1]] = 'S' _2dmap[_end[0]][_end[1]] = 'E' # input blocks while True: _block = raw_input('input block:') if not _block: break _block = _block.split(',') _block = (int(_block[0]), int(_block[1])) _2dmap[_block[0]][_block[1]] = 'X' block_node = Node(None, _block[0], _block[1]) close_list[(block_node.x, block_node.y)] = block_node print "orignal map:" print_map() if find_the_path(start, end): mark_path(end.father) print "found road as follow:" print_map()

相關推薦

A*A演算法python實現

在春節放假前兩天我偶然看到了A*演算法,感覺挺有意思。正好放假前也沒有什麼事情,就花了一個下午寫出演算法的骨架,節後又花了半天時間完善螢幕輸出的細節並且除錯完成。 該實現只是一時興起的隨手而作,沒有考慮效能和擴充套件性等問題。正在學習A*的朋友可以拿去隨便折騰

快速排序quick sortPython實現

#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/8/11 12:59 AM # @Author : Blake import random def quick_sort(array):

1001 害死人不償命的3n+1猜想 Python實現

卡拉茲(Callatz)猜想:對任何一個自然數n,如果它是偶數,那麼把它砍掉一半;如果它是奇數,那麼把(3n+1)砍掉一半。這樣一直反覆砍下去,最後一定在某一步得到n=1。卡拉茲在1950年的世界數學家大會上公佈了這個猜想,傳說當時耶魯大學師生齊動員,拼命想證明這個貌似很傻很天真的命題,結果鬧得學生們無心學業

步步學習之用python實戰機器學習1-kNN K-NearestNeighbors演算法a

我最近才開始接觸機器學習,我大學數學學的幾乎忘了,最近才接觸python。所以我以一個完全初學者角度來學習機器學習。 我主要用的書籍就是machine learning in action (機器學習實戰)這本書。我主要是用文中已有的程式碼來講解機器學習。 同時對程式碼進行

PTA 陣列迴圈左移 20 分 本題要求實現一個對陣列進行迴圈左移的簡單函式:一個數組a中存有n>0個整數,在不允許使用另外陣列的前提下,將每個整數迴圈向左移m≥0個位置,即將a中的

陣列迴圈左移 (20 分) 本題要求實現一個對陣列進行迴圈左移的簡單函式:一個數組a中存有n(>0)個整數,在不允許使用另外陣列的前提下,將每個整數迴圈向左移m(≥0)個位置,即將a中的資料由(a​0​​a​1​​⋯a​n−1​​)變換為(a​m​​⋯a​n−

決策樹ID3 C4,5 減枝 CART演算法以及Python實現

演算法簡述 在《統計學習方法》中,作者的if-then的描述,簡單一下子讓人理解了決策樹的基本概念。 決策樹,就是一個if-then的過程。 本文主要學習自《統計學習方法》一書,並努力通過書中數學推導來

N數碼問題的啟發式搜尋演算法--A*演算法python實現

一、啟發式搜尋:A演算法 1)評價函式的一般形式 : f(n) = g(n) + h(n) g(n):從S0到Sn的實際代價(搜尋的橫向因子) h(n):從N到目標節點的估計代價,稱為啟發函式(搜尋的縱向因子); 特點: 效率高, 無回溯,   搜尋演算法 OPEN表 : 存放待擴充套件的節點. CLOS

機器學習實戰第二篇-k-近鄰演算法Python實現

      上一篇幅中,我們介紹了k-近鄰演算法的基本概念、具體的分析步驟和分析方法,本篇中我們將介紹如何通過Python工具實現一個k-近鄰演算法。 1. 準備-使用Python匯入資料     首

【機器學習演算法-python實現】決策樹-Decision tree1 資訊熵劃分資料集

1.背景          決策書演算法是一種逼近離散數值的分類演算法,思路比較簡單,而且準確率較高。國際權威的學術組織,資料探勘國際會議ICDM (the IEEE International Con

機器學習經典演算法詳解及Python實現--線性迴歸Linear Regression演算法

(一)認識迴歸 迴歸是統計學中最有力的工具之一。機器學習監督學習演算法分為分類演算法和迴歸演算法兩種,其實就是根據類別標籤分佈型別為離散型、連續性而定義的。顧名思義,分類演算法用於離散型分佈預測,如前

聚類之均值聚類k-means演算法python實現

# -*- coding: UTF-8 -*- import numpy import random import codecs import copy import re import matplotlib.pyplot as plt def calcuDistance(vec1, vec2):

K最近鄰演算法KNN---sklearn+python實現

def main(): import numpy as np from sklearn import datasets digits=datasets.load_digits() x=digits.data y=digits.target from sklear

協同過濾演算法之基於物品的推薦演算法python實現

一、背景介紹 網際網路的迅猛發展將人類帶入了資訊社會和網路經濟時代,資訊化影響到了生活的方方面面。但是隨著網際網路產業的擴大,為使用者提供更多選的同時也帶來了篩選與推薦的難題。於是便提出了推薦演算法幫助使用者快速找到自己喜愛的東西。例如京東、淘寶、美團等

【機器學習演算法-python實現】KNN-k近鄰演算法實現附原始碼

 下載地址 kNN演算法及例項原始碼實現#coding=utf-8 ''' Created on Sep 16, 2010 kNN: k Nearest Neighbors Input: inX: vector to compare to existing dataset (1xN)

人臉識別演算法-特徵臉方法Eigenfacepython實現

這幾天無聊,正好想起來以前誰說有同學做人臉識別,感覺好高大上,所以找來一些基礎的人臉識別演算法來自己實現一下,正好鍛鍊一下numpy的使用。 特徵臉方法基本是將人臉識別推向真正可用的第一種方法,瞭解一下還是很有必要的。特徵臉用到的理論基礎PCA我在這裡就不說了,百度一大

鳶尾花三種聚類演算法K-means,AGNES,DBScanpython實現

一.分散性聚類(kmeans) 演算法流程: 1.選擇聚類的個數k. 2.任意產生k個聚類,然後確定聚類中心,或者直接生成k箇中心。 3.對每個點確定其聚類中心點。 4.再計算其聚類新中心。 5.重複以上步驟直到滿足收斂要求。(通常就是確定的中心點不再改變。

基本A*演算法python實現

# -*- coding: utf-8 -*-import math#地圖tm = ['############################################################','#...............................................

TF-IDF演算法-Python實現附原始碼

一、背景         TF-IDF演算法全稱 termfrequency–inverse document frequency,是一種用於資訊檢索與資訊探勘的常用加權技術。它的演算法複雜度並不高,但能很好的滿足搜尋高相關度文件的需求。由於它的高效性,TF-IDF 模型在搜尋引擎等實際應用中被廣泛使用

SVM支援向量機-《機器學習實戰》SMO演算法Python實現5

經過前幾篇文章的學習,SVM的優化目標,SMO演算法的基本實現步驟,模型對應引數的選擇,我們已經都有了一定的理解,結合《機器學習實戰》,動手實踐一個基本的SVM支援向量機,來完成一個簡單的二分類任務。建立模型之前,首先看一下我們的資料,然後再用支援向量機實現分類:     

資料探勘入門系列教程Apriori演算法Python實現

資料探勘入門系列教程(五)之Apriori演算法Python實現載入資料集獲得訓練集頻繁項的生成生成規則獲得support獲得confidence獲得Lift進行驗證總結參考 資料探勘入門系列教程(五)之Apriori演算法Python實現 在上一篇部落格中,我們介紹了Apriori演算法的演算法流