Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Given a two-dimensional grid, each cell of which contains an integer cost which represents a cost to traverse through that cell, we need to find a path from the top left cell to the bottom right cell by which the total cost incurred is minimum.
Note: It is assumed that negative cost cycles do not exist in input matrix.
This problem is an extension of problem: Min Cost Path with right and bottom moves allowed.
In the previous problem only going right and the bottom was allowed but in this problem, we are allowed to go bottom, up, right and left i.e. in all 4 directions.
A cost grid is given in below diagram, minimum cost to reach bottom right from top left is 327 (= 31 + 10 + 13 + 47 + 65 + 12 + 18 + 6 + 33 + 11 + 20 + 41 + 20) The chosen least cost path is shown in green.
It is not possible to solve this problem using dynamic programming similar to the previous problem because here current state depends not only on the right and bottom cells but also on the left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of the grid represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph from these cells instead we will use the matrix as it is in our Dijkstra’s algorithm.
In the below code, Dijkstra’s algorithm’s implementation is used. The code implemented below is changed to cope with matrix represented implicit graph. Please also see use of dx and dy arrays in the below code, these arrays are taken for simplifying the process of visiting neighbor vertices of each cell.
Below is the implementation of the above approach:
Time Complexity: O(N2 log N)
Auxiliary Space: O(N2)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.