Question

In: Computer Science

Python: Implement a grid-maze solving program that uses depth-first search to solve grids. The agent’s actions...

Python: Implement a grid-maze solving program that uses depth-first search to solve grids. The agent’s actions are moving in one of four directions: up, down, left, and right.

A grid is formatted like below where 1’s represent locations the agent cannot traverse:

1 1 1 1 1 1 1 1

1 0 0 0 1 1 1 1

1 0 0 0 0 0 0 1

1 1 1 0 0 1 0 1

1 0 1 0 0 1 0 1

1 0 0 0 0 0 0 1

1 1 1 1 1 1 1 1

The final path can be displayed with ‘S’ for the initial state, ‘G’ for the goal state, and ‘*’ symbols for the path:

1 1 1 1 1 1 1 1

1 S 0 0 1 1 1 1

1 * * * 0 0 0 1

1 1 1 * 0 1 0 1

1 0 1 * G 1 0 1

1 0 0 0 0 0 0 1

1 1 1 1 1 1 1 1

Solutions

Expert Solution

For given output, just copy paste it

# Check if it is possible to go to (x, y) from current position. The
# function returns false if the cell has value 0 or already visited

M = 7
N=8

def isSafe(mat, visited, x, y):
    return not (mat[x][y] == 1 or visited[x][y])


# if not a valid position, return false
def isValid(x, y):
    return M > x >= 0 and N > y >= 0


# Find Shortest Possible Route in a Matrix mat from source cell (0, 0)
# to destination cell (x, y)

# 'min_dist' stores length of longest path from source to destination
# found so far and 'dist' maintains length of path from source cell to
# the current cell (i, j)

v = [[0 for x in range(N)] for y in range(M)]


def findShortestPath(mat, visited, i, j, x, y, min_dist=float('inf'), dist=0):

    # if destination is found, update min_dist
    
    if i==x and j==y:
        # print (min_dist);
      if dist<min_dist:
         min_dist=dist;
         for i in range(M):
                for j in range(N):
                    if visited[i][j]==True:
                        v[i][j]=1;
                    else:
                        v[i][j]=0;
         return min_dist;

           
        

    # set (i, j) cell as visited
    visited[i][j] = 1

    # go to bottom cell
    if isValid(i + 1, j) and isSafe(mat, visited, i + 1, j):
        min_dist = findShortestPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1)

    # go to right cell
    if isValid(i, j + 1) and isSafe(mat, visited, i, j + 1):
        min_dist = findShortestPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1)

    # go to top cell
    if isValid(i - 1, j) and isSafe(mat, visited, i - 1, j):
        min_dist = findShortestPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1)

    # go to left cell
    if isValid(i, j - 1) and isSafe(mat, visited, i, j - 1):
        min_dist = findShortestPath(mat, visited, i, j - 1, x, y, min_dist, dist + 1)

    # Backtrack - Remove (i, j) from visited matrix
    visited[i][j] = 0

    return min_dist


if __name__ == '__main__':

    mat = [
[1 ,1 ,1 ,1 ,1 ,1 ,1 ,1],

[1 ,0,0, 0 ,1 ,1 ,1, 1],

[1 ,0 ,0 ,0 ,0 ,0, 0 ,1],

[1 ,1, 1, 0, 0, 1, 0, 1],

[1, 0 ,1 ,0 ,0 ,1 ,0 ,1],

[1 ,0 ,0 ,0 ,0 ,0 ,0, 1],


[1, 1, 1, 1 ,1 ,1 ,1 ,1]
    ]

    


    si=1;  // starting index x -coord
    sj=1;
    
    ei=4;
    ej=4;
       # construct a matrix to keep track of visited cells
    visited = [[0 for x in range(N)] for y in range(M)]

    min_dist = findShortestPath(mat, visited, si, sj, ei, ej)
    
    for i in range(M):
        for j in range(N):
            if i==si and j==sj:
                print("S", end=" ")
            elif i==ei and j==ej:
                print("G", end=" ")
            elif v[i][j]==True:
                print("*", end=" ")
            else:
                print(mat[i][j], end=" ")
            
        print("\n")    
        

    if min_dist != float('inf'):
        print("The shortest path from source to destination has length", min_dist)
    else:
        print("Destination can't be reached from source")

Related Solutions

Write a Java program that implements the Depth-First Search (DFS) algorithm. Input format: This is a...
Write a Java program that implements the Depth-First Search (DFS) algorithm. Input format: This is a sample input from a user. 3 2 0 1 1 2 The first line (= 3 in the example) indicates that there are three vertices in the graph. You can assume that the first vertex starts from the number 0. The second line (= 2 in the example) represents the number of edges, and following two lines are the edge information. This is the...
Can you solve it with hand solving, not the program solving? Let us now assume that...
Can you solve it with hand solving, not the program solving? Let us now assume that we have continuous time instead of discrete time, that S(0) = 100, r = 0.03, σ = 0.4 and T = 1. Calculate the price at t = 0 of the same European call option as above, i.e. X = max{S(1) − 104, 0}.
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is similar to binary search, except it tries to begin the search nearer to the location of the item. Instead of the using the middle value of the sorted array, interpolation search estimates the location of the target with respect to the first & last values in the array. The implementation is the same as binary search except that you should calculate the mid value...
write a python program that will search through a range of launch angles (this will require...
write a python program that will search through a range of launch angles (this will require a loop statement) the target is 500 meters away and the projectile was launched at 100m/s, the initial height of the projectile can be between 2 and 30 meters the print statement will state the initial launch angle required to hit the target from the projectile height. ***explain each step or a rating will not be given***
Design and implement a program in python that takes a list of items along with quantities...
Design and implement a program in python that takes a list of items along with quantities or weights. The program should include at least two function definition that is called within the main part of your program. Each item has a price associated by quantity or weight. The user enters the item along with the quantity or weight and the program prints out a table for each item along with the quantity/weight and total price. Your program should be able...
Python 10 - (10 pts) - Implement a program that starts by asking the user to...
Python 10 - (10 pts) - Implement a program that starts by asking the user to enter a userID (i.e., a string). The program then checks whether the id entered by the user is in the list of valid users. The current user list is: ['joe', 'sue', jamal, 'sophie'] Depending on the outcome, an appropriate message should be printed. Regardless of the outcome, your function should print 'Done.' before terminating. Here is an example of a successful login: >>> Login:...
IN PYTHON Write a program to do the following: Solve the a set of equations as...
IN PYTHON Write a program to do the following: Solve the a set of equations as mentioned in "Zybook 5.20 LAB: Brute force equation solver". Instead of the arithmetic operators use your own function defined in a module named calc. You must provide two files (calc.py, brute_force_solver.py) :- 1) calc.py:- Add function named 'add' instead of using operator '+' [10pts] Add function named 'difference' instead of using operator '-' [10pts] Add function named 'product' instead of using operator '*' [10pts]...
Write a program in C++ to implement Binary Search Algorithm. Assume the data given in an...
Write a program in C++ to implement Binary Search Algorithm. Assume the data given in an array. Use number of data N at least more than 10. The function Binary Search should return the index of the search key V.
write a python program, please. Create a program that uses the Gettysburg Address as input and...
write a python program, please. Create a program that uses the Gettysburg Address as input and outputs a list of tuples for every two words. For example: [('Four', 'score'),('and', 'seven'), ...].
Design and implement a Python program which will allow two players to play the game of...
Design and implement a Python program which will allow two players to play the game of Tic-Tac-Toe in a 4x4 grid! X | O | X | O -------------- O | O | X | O -------------- X | X | O | X -------------- X | X | O | X The rules for this game is the same as the classic, 3x3, game – Each cell can hold one of the following three strings: "X", "O", or "...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT