Creating a maze graph in python

Hey, I'm trying to make a graph using dictionaries in Python. I am using a txt file containing a maze (b for walls a for paths), and I am trying to make a dictionary that lists all the possible steps that need to be taken in the maze (simple steps, not full paths). Any ideas on where I should start? I have never worked with dictionaries.

Thank you so much for the help that started me very well. One more question: I start in one virtual house and check all possible ways. after this, the patient must move to another house and check the path on this. How can I make sure that I am not getting an endless loop or double-checking an already verified home?

+4
source share
2 answers

Assuming your maze looks like a grid, the position in the maze can be represented as a tuple (line, col). When you build a dictionary, create an entry for each position in the maze, the initial value is an empty list. In each actual position (r, c) in the maze, you can find out if you can get (r-1, c), (r, c-1), (r + 1, c) and (r, c + 1) . If you can, add this tuple to the list. So, let's say that I can get to (r-1, c) and (r, c + 1) from (r, c), the entry in the dictionary will look like

  maze_dict[(r,c)] = [(r-1,c), (r,c+1)] 

To create an empty dictionary, you should use:

 maze_dict = {} 

You should also familiarize yourself with the dictionaries in the python lesson.

+4
source

Thank you so much for the help that started me very well. Just one more question, I start in one virtual house and check all possible paths. after this, patients will have to move to another house and check the path on this. How can I make sure that I am not getting an endless loop or double-checking an already verified home?

Create a Home class with your grid coordinates:

 class House(object): def __init__(self, pos): self.pos = pos # the coordinates (position) on the grid, a tuple self.paths = [] # Empty array to hold paths 

Create some houses:

 houses = [House((1,3)), House((3,3)), House((4,3))] # a list of houses 

Now go through each house and dip its path (s)

 paths = {} paths[(1,3)] = [(2,3), (4,3) ... ] # possible paths to the point (1,3) for i in houses: try: i.paths = paths[(i.pos)] except KeyError: print "I don't know how to get to ", i.pos 

Going through the list ensures that you check each house only once. Now you can find out about unreachable homes:

 for i in houses: if not i.paths: print "I did not find a way to reach the house at ",i.pos 
+1
source

Source: https://habr.com/ru/post/1335910/


All Articles