I'm attempting to implement BFS in Python, I understand how the algorithm works but I don't have much programming experience. I've spent hours thinking about the best way to represent everything and how to be as efficient as possible. I've been unable to figure out how to get the path from my start node, to goal node.
I've spent ages googling around and looking at other peoples implementation of the algorithm, but my application is slightly different and this confuses me. When people are implementing BFS, they are assuming they have a graph given to them (as does the wikipedia article on BFS). In my problem, I have an initial state and a goal state I want to reach, but no graph or tree so I'm generating the nodes as I go.
For example:
def BFS(initial, goal):
q = [initial]
visited = []
while q:
n = q.pop()
states = generate_states(n)
for state in states:
if state == goal:
pass #placeholder
q.append(state)
visited.append(state)
It's not properly fleshed out because I'm having trouble with something, I'm not sure what it specifically is either... If initial and goal are nodes, and I write a struct type class elsewhere in my code such as:
class node:
state = None
parent = None
I think this is a suitable way to represent a node. So when I pop a node object off my queue, it has information regarding where it originated which will be initialized by the generate_states function. Then the for loop will append each of these new nodes onto the queue, and visited queue and it will repeated under one of the generated nodes has a state which matches my goal state.
Now that I've found the goal node, I have a list of visited nodes, but if I trace the path the path backwards from the goal node, aren't I slowing down the algorithm? Once a goal has been found I would look at its parent, locate its parent in the visited list, then look at the parent of the parent, etc... until I had a path = [node object, node object, ...] from the initial node to the goal node.
This brings me to another problem, when I create a node object it only lasts for one iteration of the while loop. How am I meant to store the objects in an array, they will each need a unique name and there is no obvious way (to me) to do this. This was the problem I mentioned earlier that I wasn't sure about. So it looks like I'm creating nodes but then only storing the node.state in the queue, which is pointless because I require the node object to access node.parent...
Why am I finding this so difficult, am I missing something obvious or making this too complicated?
Thanks for reading.