Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
maze solution
#1
Dear all,
I am stuck with this code. It appears to be working for most of the situations. But for this particular maze, it fails. I have a 2D array of 0/1 where 0 represents the wall and I am trying to get from point start to point end in the shortest manner.
Here is the code and below is the maze for which it fails. I would really appreciate any input.
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import time
 
import os
 
 
 
basic_operations = 0
 
 
 
 
 
def main():
 
    i = 0
 
    for file in os.listdir():
 
        if file.startswith("maze") and file.endswith(".txt"):
 
            
            i += 1
 
            print("Maze", i)
            if i==1:
                maze = readMazeFromFile(file)
                printMaze(maze)
                maze = convertmaze(maze)
     
                start = findStart(maze)
 
                end = findEnd(maze)
 
 
                printMaze(maze)
                startTime = time.time()
 
                path = BFS(maze, start, end)
 
                endTime = time.time()
 
 
 
                if path == None:
 
                    printMaze(maze)
 
                    print("No path to destination.")
 
                else:
 
                    printPath(maze, path)
 
                    print("Shortest path: ")
 
                    print(path)
                    print(len(path))
 
 
 
                print("Time taken:", endTime-startTime, "secs")
 
                print("Basic operations: ", basic_operations)
 
                print("\n")
 
 
 
 
 
def BFS(maze, start, end):
 
    '''"Brute-Force Search"
 
    :param maze(list): the maze to be navigated
 
    :param start(tuple): the starting coordinates (row, col)
 
    :param end(tuple): the end coordinates (row, col)
 
    :return: shortest path from start to end
 
    '''
 
    queue = [start]
 
    visited = set()
 
 
 
    while len(queue) != 0:
 
        if queue[0] == start:
 
            path = [queue.pop(0)]  # Required due to a quirk with tuples in Python
 
        else:
 
            path = queue.pop(0)
 
        front = path[-1]
 
        if front == end:
 
            return path
 
        elif front not in visited:
 
            for adjacentSpace in getAdjacentSpaces(maze, front, visited):
 
                newPath = list(path)
 
                newPath.append(adjacentSpace)
 
                queue.append(newPath)
 
                global basic_operations
 
                basic_operations += 1
 
            visited.add(front)
 
    return None
 
 
 
 
 
def getAdjacentSpaces(maze, space, visited):
 
    ''' Returns all legal spaces surrounding the current space
 
    :param space: tuple containing coordinates (row, col)
 
    :return: all legal spaces
 
    '''
 
    spaces = list()
 
    spaces.append((space[0]-1, space[1]))  # Up
 
    spaces.append((space[0]+1, space[1]))  # Down
 
    spaces.append((space[0], space[1]-1))  # Left
 
    spaces.append((space[0], space[1]+1))  # Right
 
     
 
    final = list()
 
    for i in spaces:
        print(i[0])
        print(i[1])
        if maze[i[0]][i[1]] != '*' and i not in visited:
 
            final.append(i)
 
    return final
 
 
 
 
 
def findStart(maze):
 
    for i in range(len(maze)):
 
        for j in range(len(maze[0])):
 
            if maze[i][j] == 's':
 
                return tuple([i, j])
 
    return None
 
 
 
 
 
def findEnd(maze):
 
    for i in range(len(maze)):
 
        for j in range(len(maze[0])):
 
            if maze[i][j] == 'e':
 
                return tuple([i, j])
 
    return None
 
 
 
 
 
def readMazeFromFile(f):
 
    maze = list()
 
    with open(f) as file:
 
        for line in file:
 
            maze.append(list(line.rstrip()))
 
    return maze
 
def convertmaze(maze):
    for i in range(len(maze)):
        for j in range(len(maze[0])):
            if maze[i][j]=='0':
                maze[i][j]='*'
            if maze[i][j]=='1':
                maze[i][j]='.'
    return maze
 
 
def printMaze(maze):
 
    for i in range(len(maze)):
 
        for j in range(len(maze[0])):
 
            print(maze[i][j], end="")
 
        print()
 
 
 
 
 
def printPath(maze, path):
 
    for i in range(len(maze)):
 
        for j in range(len(maze[0])):
 
            if tuple([i, j]) in path and maze[i][j] != 's' and maze[i][j] != 'e':
 
                print("x", end="")
 
            else:
 
                print(maze[i][j], end="")
 
        print()
And here is the maze where it fails:
00000000000000000000
00111111111111111s11
00000001000000001100
01000101000001111000
10111011000000101000
10000010000000101001
111111e1111111111000
11111111110000000000
Reply
#2
I observe that 'e' is accessible only diagonally.

My mistake.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
for example, this one works just fine:
00000000000000000000
001s1111111111111111
00000001000000001100
01000101000001111000
10111011000000101000
10000010000000101001
111111e1111111111000
11111111110000000000
Reply
#4
Being more specific about the problem would have been helpful (as in the full text of the error message).

I get an index error in getAdjacentSquares. When you add squares, you are not checking to see if the added squares are actually in the maze. So it starts at the 's', goes to the right, and causes an error. Either you need to specify that all of your mazes have walls around the borders, which would seem odd, or you need to check each square with a conditional before entering it. Horizontal coordinates need to be 0 <= coordinate < len(maze[0], and vertical coordinates need to be 0 <= coordinate <= len(maze). Note that you will need four conditionals, one for each square added.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Hi,
yes, this is exactly where I get the message. Could you please help me where is the best place to do such check? And after checking it, do I do anything specific to the square?
Thank you!
Reply
#6
You need to do one check before each square is appended, depending on how you are modifying the coordinates. If you are subtracting, you need to make sure the number is at least 0. If you are adding, you need to make sure the number is less than the appropriate len. If it passes the check, add the square, otherwise move on to the next square.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem about maze path finder Simurg 2 2,743 Aug-16-2020, 01:10 PM
Last Post: Simurg
  Maze Mapping with Image Processing furkankuyumcu 0 2,748 Dec-16-2018, 02:45 PM
Last Post: furkankuyumcu
  Understanding maze generation code kleynah22 1 3,888 Nov-11-2017, 02:09 PM
Last Post: sparkz_alot
  maze pattern angelbest4 1 3,346 Sep-03-2017, 12:09 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020