I am trying to implement a * a search algorithm in python in a grid with a 6 * 6 connection to a w630 network, using networkx to organize nodes and matplotlib to display. It works for me, so it finds the shortest path, but without heuristics this is just a crude search attempt, which is too expensive. How to assign x, y coordinates to my nodes when I create them, or is there any other way to get the heuristic to work? (I know that networkx has a built-in function * that I could use, but I want to demonstrate that I can implement the algorithm)
Here's the code (a bit messy from StackOverflow formatting):
import networkx as nx G=nx.Graph() import matplotlib.pyplot as plt def add_nodes(): G.add_nodes_from([0, 1, 2, 3, 4, 5, \ 6, 7, 8, 9, 10, 11, \ 12, 13, 14, 15, 16, 17, \ 18, 19, 20, 21, 22, 23, \ 24, 25, 26, 27, 28, 29,\ 30, 31, 32, 33, 34, 35]) c = 0 for y in range (0,5): for x in range (0,5): G.add_node(c, pos=(x/10,y/10)) c=c+1 #http://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value #prev code for brute force search: #https://pastebin.com/DT76bvw5 #node pos: http://stackoverflow.com/questions/11804730/networkx-add-node-with-specific-position #http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html #http://zurb.com/forrst/posts/A_algorithm_in_python-B4c for a in G.nodes(): if a not in (5, 11, 17, 23,29, 35): G.add_edge(a, a+1) if a not in (30, 31, 32, 33, 34, 35): G.add_edge(a, a+6) if a not in (5, 11, 17, 23, 29, 30, 31, 32, 33, 34, 35): G.add_edge(a, a+7) if a not in (0, 6, 12, 18, 24, 30, 31, 32, 33, 34, 35): G.add_edge(a, a+5) def heuristic(a, b): (x1, y1) = a (x2, y2) = b return abs(x1-x2) + abs(y1-y2)