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

PYTHON PROBLEM: Goal: Design and implement a Python program to solve the following problem. Scientists measure...
PYTHON PROBLEM: Goal: Design and implement a Python program to solve the following problem. Scientists measure an object’s mass in kilograms and weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the following formula: [Note: Use or test any random numbers to check whether the weight is heavy, can be lifted or light] ????h? = ???? × 9.8 Write a program that asks the user to...
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...
In this assignment, you will implement Breadth First Search (BFS). The input to your program is...
In this assignment, you will implement Breadth First Search (BFS). The input to your program is a graph in the adjacency list format. The input graph has at most 100 vertices. Your program must initiate a BFS from vertex 2 of the graph. If the graph is connected, your program must output “Graph is connected”. If the graph is disconnected, your program must output “Graph is not connected”. Your program should read from an input file: data2.txt and write to...
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...
Solving Problems Using Recursion (Python): To solve the problem, you have to use recursion and cannot...
Solving Problems Using Recursion (Python): To solve the problem, you have to use recursion and cannot use for or while loops to solve the problems as well as not using global variables. 1. Create a function that takes a positive integer and returns it with neighboring digits removed. Do not convert the integer to a list. Ex. Input = [5555537777721] Output = [53721]
Assume you need to write a Java program that uses a binary search algorithm to search...
Assume you need to write a Java program that uses a binary search algorithm to search a sorted array for a given value. 1. Write a Java pseudocode that uses recursion to accomplish the task. Here is a hint. When you are searching for a particular value in an array, there are two possible outcomes. 1) The value is found and the array index of that value is returned. 2) The value is not found and we return -1. (5...
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***
Question(on Python). There is a Python program what could solve the simple slide puzzles problem by...
Question(on Python). There is a Python program what could solve the simple slide puzzles problem by A* algorithm. Please fill in the body of the a_star() function. In order to solve a specific problem, the a_star function needs to know the problem's start state, the desired goal state, and a function that expands a given node. To be precise, this function receives as its input the current state and the goal state and returns a list of pairs of the...
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]...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT