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.
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 1,954 Aug-16-2020, 01:10 PM
Last Post: Simurg
  Maze Mapping with Image Processing furkankuyumcu 0 2,191 Dec-16-2018, 02:45 PM
Last Post: furkankuyumcu
  Understanding maze generation code kleynah22 1 3,257 Nov-11-2017, 02:09 PM
Last Post: sparkz_alot
  maze pattern angelbest4 1 2,704 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