The Wayback Machine - https://web.archive.org/web/20240907070224/https://www.geeksforgeeks.org/minimum-cost-path-left-right-bottom-moves-allowed/
Open In App

Minimum Cost Path with Left, Right, Bottom and Up moves allowed

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Hard
26.99%
1.1L

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.

Examples:

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:

C++




// C++ program to get least cost path in a grid from
// top-left to bottom-right
 
#include <bits/stdc++.h>
 
using namespace std;
 
#define ROW 5
#define COL 5
 
// structure for information of each cell
struct cell {
    int x, y;
    int distance;
    cell(int x, int y, int distance)
        : x(x)
        , y(y)
        , distance(distance)
    {
    }
};
 
// Utility method for comparing two cells
bool operator<(const cell& a, const cell& b)
{
    if (a.distance == b.distance) {
        if (a.x != b.x)
            return (a.x < b.x);
        else
            return (a.y < b.y);
    }
    return (a.distance < b.distance);
}
 
// Utility method to check whether a point is
// inside the grid or not
bool isInsideGrid(int i, int j)
{
    return (i >= 0 && i < ROW && j >= 0 && j < COL);
}
 
// Method returns minimum cost to reach bottom
// right from top left
int shortest(int grid[ROW][COL], int row, int col)
{
    int dis[row][col];
 
    // initializing distance array by INT_MAX
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            dis[i][j] = INT_MAX;
 
    // direction arrays for simplification of getting
    // neighbour
    int dx[] = { -1, 0, 1, 0 };
    int dy[] = { 0, 1, 0, -1 };
 
    set<cell> st;
 
    // insert (0, 0) cell with 0 distance
    st.insert(cell(0, 0, 0));
 
    // initialize distance of (0, 0) with its grid value
    dis[0][0] = grid[0][0];
 
    // loop for standard dijkstra's algorithm
    while (!st.empty()) {
        // get the cell with minimum distance and delete
        // it from the set
        cell k = *st.begin();
        st.erase(st.begin());
 
        // looping through all neighbours
        for (int i = 0; i < 4; i++) {
            int x = k.x + dx[i];
            int y = k.y + dy[i];
 
            // if not inside boundary, ignore them
            if (!isInsideGrid(x, y))
                continue;
 
            // If distance from current cell is smaller,
            // then update distance of neighbour cell
            if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) {
                // If cell is already there in set, then
                // remove its previous entry
                if (dis[x][y] != INT_MAX)
                    st.erase(
                        st.find(cell(x, y, dis[x][y])));
 
                // update the distance and insert new
                // updated cell in set
                dis[x][y] = dis[k.x][k.y] + grid[x][y];
                st.insert(cell(x, y, dis[x][y]));
            }
        }
    }
 
    // uncomment below code to print distance
    // of each cell from (0, 0)
    /*
    for (int i = 0; i < row; i++, cout << endl)
        for (int j = 0; j < col; j++)
            cout << dis[i][j] << " ";
    */
    // dis[row - 1][col - 1] will represent final
    // distance of bottom right cell from top left cell
    return dis[row - 1][col - 1];
}
 
// Driver code to test above methods
int main()
{
    int grid[ROW][COL]
        = { 31, 100, 65,  12,  18,  10, 13, 47,  157,
            6,  100, 113, 174, 11,  33, 88, 124, 41,
            20, 140, 99,  32,  111, 41, 20 };
 
    cout << shortest(grid, ROW, COL) << endl;
    return 0;
}


Java




// Java program to get least cost path
// in a grid from top-left to bottom-right
import java.io.*;
import java.util.*;
 
class GFG{
     
static int[] dx = { -1, 0, 1, 0 };
static int[] dy = { 0, 1, 0, -1 };
static int ROW = 5;
static int COL = 5;
 
// Custom class for representing
// row-index, column-index &
// distance of each cell
static class Cell
{
    int x;
    int y;
    int distance;
     
    Cell(int x, int y, int distance)
    {
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}
 
// Custom comparator for inserting cells
// into Priority Queue
static class distanceComparator
  implements Comparator<Cell>
{
    public int compare(Cell a, Cell b)
    {
        if (a.distance < b.distance)
        {
            return -1;
        }
        else if (a.distance > b.distance)
        {
            return 1;
        }
        else {return 0;}
    }
}
 
// Utility method to check whether current
// cell is inside grid or not
static boolean isInsideGrid(int i, int j)
{
    return (i >= 0 && i < ROW &&
            j >= 0 && j < COL);
}
 
// Method to return shortest path from
// top-corner to bottom-corner in 2D grid
static int shortestPath(int[][] grid, int row,
                                      int col)
{
    int[][] dist = new int[row][col];
     
    // Initializing distance array by INT_MAX
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < col; j++)
        {
            dist[i][j] = Integer.MAX_VALUE;
        }
    }
     
    // Initialized source distance as
    // initial grid position value
    dist[0][0] = grid[0][0];
     
    PriorityQueue<Cell> pq = new PriorityQueue<Cell>(
                  row * col, new distanceComparator());
                   
    // Insert source cell to priority queue
    pq.add(new Cell(0, 0, dist[0][0]));
    while (!pq.isEmpty())
    {
        Cell curr = pq.poll();
        for(int i = 0; i < 4; i++)
        {
            int rows = curr.x + dx[i];
            int cols = curr.y + dy[i];
             
            if (isInsideGrid(rows, cols))
            {
                if (dist[rows][cols] >
                    dist[curr.x][curr.y] +
                    grid[rows][cols])
                {
                     
                    // If Cell is already been reached once,
                    // remove it from priority queue
                    if (dist[rows][cols] != Integer.MAX_VALUE)
                    {
                        Cell adj = new Cell(rows, cols,
                                       dist[rows][cols]);
                                        
                        pq.remove(adj);
                    }
                     
                    // Insert cell with updated distance
                    dist[rows][cols] = dist[curr.x][curr.y] +
                                       grid[rows][cols];
                                        
                    pq.add(new Cell(rows, cols,
                               dist[rows][cols]));
                }
            }
        }
    }
    return dist[row - 1][col - 1];
}
 
// Driver code
public static void main(String[] args)
throws IOException
{
    int[][] grid = { { 31, 100, 65, 12, 18 },
                     { 10, 13, 47, 157, 6 },
                     { 100, 113, 174, 11, 33 },
                     { 88, 124, 41, 20, 140 },
                     { 99, 32, 111, 41, 20 } };
                      
    System.out.println(shortestPath(grid, ROW, COL));
}
}
 
// This code is contributed by jigyansu


Python3




# Python program to get least cost path in a grid from
# top-left to bottom-right
from functools import cmp_to_key
 
ROW = 5
COL = 5
 
def mycmp(a,b):
     
    if (a.distance == b.distance):
        if (a.x != b.x):
            return (a.x - b.x)
        else:
            return (a.y - b.y)
    return (a.distance - b.distance)
 
# structure for information of each cell
class cell:
 
    def __init__(self,x, y, distance):
        self.x = x
        self.y = y
        self.distance = distance
 
# Utility method to check whether a point is
# inside the grid or not
def isInsideGrid(i, j):
    return (i >= 0 and i < ROW and j >= 0 and j < COL)
 
# Method returns minimum cost to reach bottom
# right from top left
def shortest(grid, row, col):
    dis = [[0 for i in range(col)]for j in range(row)]
 
    # initializing distance array by INT_MAX
    for i in range(row):
        for j in range(col):
            dis[i][j] = 1000000000
 
    # direction arrays for simplification of getting
    # neighbour
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
 
    st = []
 
    # insert (0, 0) cell with 0 distance
    st.append(cell(0, 0, 0))
 
    # initialize distance of (0, 0) with its grid value
    dis[0][0] = grid[0][0]
 
    # loop for standard dijkstra's algorithm
    while (len(st)!=0):
 
        # get the cell with minimum distance and delete
        # it from the set
        k = st[0]
        st = st[1:]
 
        # looping through all neighbours
        for i in range(4):
 
            x = k.x + dx[i]
            y = k.y + dy[i]
 
            # if not inside boundary, ignore them
            if (isInsideGrid(x, y) == 0):
                continue
 
            # If distance from current cell is smaller, then
            # update distance of neighbour cell
            if (dis[x][y] > dis[k.x][k.y] + grid[x][y]):
                # update the distance and insert new updated
                # cell in set
                dis[x][y] = dis[k.x][k.y] + grid[x][y]
                st.append(cell(x, y, dis[x][y]))
 
        st.sort(key=cmp_to_key(mycmp))
 
    # uncomment below code to print distance
    # of each cell from (0, 0)
 
    # for i in range(row):
    #     for j in range(col):
    #         print(dis[i][j] ,end= " ")
    #     print()
 
    # dis[row - 1][col - 1] will represent final
    # distance of bottom right cell from top left cell
    return dis[row - 1][col - 1]
 
# Driver code to test above methods
 
grid = [[31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140],[99, 32, 111, 41, 20]]
print(shortest(grid, ROW, COL))
 
# This code is contributed by shinjanpatra


C#




using System;
using System.Collections.Generic;
 
class GFG {
    static int[] dx = { -1, 0, 1, 0 };
    static int[] dy = { 0, 1, 0, -1 };
    static int ROW = 5;
    static int COL = 5;
 
    // Custom class for representing
    // row-index, column-index &
    // distance of each cell
    class Cell {
        public int x;
        public int y;
        public int distance;
 
        public Cell(int x, int y, int distance)
        {
            this.x = x;
            this.y = y;
            this.distance = distance;
        }
    }
 
    // Custom comparator for sorting cells
    // in ascending order of distance
    class DistanceComparer : IComparer<Cell> {
        public int Compare(Cell a, Cell b)
        {
            if (a.distance < b.distance) {
                return -1;
            }
            else if (a.distance > b.distance) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
 
    // Utility method to check whether current
    // cell is inside grid or not
    static bool IsInsideGrid(int i, int j)
    {
        return (i >= 0 && i < ROW && j >= 0 && j < COL);
    }
 
    // Method to return shortest path from
    // top-corner to bottom-corner in 2D grid
    static int ShortestPath(int[][] grid, int row, int col)
    {
        int[][] dist = new int[row][];
        for (int i = 0; i < row; i++) {
            dist[i] = new int[col];
            for (int j = 0; j < col; j++) {
                dist[i][j] = int.MaxValue;
            }
        }
 
        // Initialized source distance as
        // initial grid position value
        dist[0][0] = grid[0][0];
 
        List<Cell> pq = new List<Cell>();
        pq.Add(new Cell(0, 0, dist[0][0]));
        pq.Sort(new DistanceComparer());
 
        while (pq.Count > 0) {
            Cell curr = pq[0];
            pq.RemoveAt(0);
 
            for (int i = 0; i < 4; i++) {
                int rows = curr.x + dx[i];
                int cols = curr.y + dy[i];
 
                if (IsInsideGrid(rows, cols)) {
                    if (dist[rows][cols]
                        > dist[curr.x][curr.y]
                              + grid[rows][cols]) {
                        // If Cell is already been reached
                        // once, remove it from list
                        if (dist[rows][cols]
                            != int.MaxValue) {
                            Cell adj = new Cell(
                                rows, cols,
                                dist[rows][cols]);
                            pq.Remove(adj);
                        }
 
                        // Insert cell with updated distance
                        dist[rows][cols]
                            = dist[curr.x][curr.y]
                              + grid[rows][cols];
                        pq.Add(new Cell(rows, cols,
                                        dist[rows][cols]));
                        pq.Sort(new DistanceComparer());
                    }
                }
            }
        }
 
        return dist[row - 1][col - 1];
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int[][] grid
            = { new int[] { 31, 100, 65, 12, 18 },
                new int[] { 10, 13, 47, 157, 6 },
                new int[] { 100, 113, 174, 11, 33 },
                new int[] { 88, 124, 41, 20, 140 },
                new int[] { 99, 32, 111, 41, 20 } };
 
        Console.WriteLine(ShortestPath(grid, ROW, COL));
    }
}
 
// This code is contributed by phasing17


Javascript




<script>
  
// Javascript program to get least cost path in a grid from
// top-left to bottom-right
var ROW = 5
var COL = 5
 
// structure for information of each cell
class cell
{
    constructor(x, y, distance)
    {
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
};
 
 
// Utility method to check whether a point is
// inside the grid or not
function isInsideGrid(i, j)
{
    return (i >= 0 && i < ROW && j >= 0 && j < COL);
}
 
// Method returns minimum cost to reach bottom
// right from top left
function shortest(grid, row, col)
{
    var dis = Array.from(Array(row), ()=>Array(col).fill(0));
 
    // initializing distance array by INT_MAX
    for (var i = 0; i < row; i++)
        for (var j = 0; j < col; j++)
            dis[i][j] = 1000000000;
 
    // direction arrays for simplification of getting
    // neighbour
    var dx = [-1, 0, 1, 0];
    var dy = [0, 1, 0, -1];
 
    var st = [];
 
    // insert (0, 0) cell with 0 distance
    st.push(new cell(0, 0, 0));
 
    // initialize distance of (0, 0) with its grid value
    dis[0][0] = grid[0][0];
 
    // loop for standard dijkstra's algorithm
    while (st.length!=0)
    {
        // get the cell with minimum distance and delete
        // it from the set
        var k = st[0];
        st.shift();
 
        // looping through all neighbours
        for (var i = 0; i < 4; i++)
        {
            var x = k.x + dx[i];
            var y = k.y + dy[i];
 
            // if not inside boundary, ignore them
            if (!isInsideGrid(x, y))
                continue;
 
            // If distance from current cell is smaller, then
            // update distance of neighbour cell
            if (dis[x][y] > dis[k.x][k.y] + grid[x][y])
            {
                // update the distance and insert new updated
                // cell in set
                dis[x][y] = dis[k.x][k.y] + grid[x][y];
                st.push(new cell(x, y, dis[x][y]));
            }
        }
        st.sort((a,b)=>{
            if (a.distance == b.distance)
    {
        if (a.x != b.x)
            return (a.x - b.x);
        else
            return (a.y - b.y);
    }
    return (a.distance - b.distance);
        });
    }
 
    // uncomment below code to print distance
    // of each cell from (0, 0)
    /*
    for (int i = 0; i < row; i++, cout << endl)
        for (int j = 0; j < col; j++)
            cout << dis[i][j] << " ";
    */
    // dis[row - 1][col - 1] will represent final
    // distance of bottom right cell from top left cell
    return dis[row - 1][col - 1];
}
 
// Driver code to test above methods
var grid =
[
    [31, 100, 65, 12, 18],
    [10, 13, 47, 157, 6],
    [100, 113, 174, 11, 33],
    [88, 124, 41, 20, 140],
    [99, 32, 111, 41, 20]
];
document.write(shortest(grid, ROW, COL));
 
// This code is contributed by rutvik_56.
 
</script>


Output

327

Time Complexity: O(N2 log N), The Dijkstra’s algorithm used in the program has a time complexity of O(E log V) where E is the number of edges and V is the number of vertices. In this program, for each cell, we check its four neighbors, so the number of edges E in the worst case would be 4 times the number of cells (N^2) in the grid. Therefore, the time complexity of the program is O(4N^2logN^2), which simplifies to O(N^2 logN).
Auxiliary Space: O(N2), In this program, we are using a 2D array to store the distances from the top-left cell to each cell in the grid. The size of this array is N^2. We are also using a set to store the cells with their distances. In the worst case, all cells in the grid could be present in the set, so the size of the set could also be N^2. Therefore, the space complexity of the program is O(N^2).

 



Previous Article
Next Article

Similar Reads

Minimize cost to reach bottom right from top left corner of Matrix with given separate cost for each move
Given an integer N and three N x N matrices X[][], Y[][], and Z[][], the task is to calculate the minimum cost required to reach the bottom right from the top left of the matrix using the following moves: Move to a cell in the right direction from (i, j) which will cost X[i][j].Move to a cell in the downward direction from (i, j) which will cost Y[
15+ min read
Find the maximum cost path from the bottom-left corner to the top-right corner
Given a two dimensional grid, each cell of which contains integer cost which represents a cost to traverse through that cell. The task is to find the maximum cost path from the bottom-left corner to the top-right corner.Note: Use up and right moves only Examples: Input : mat[][] = {{20, -10, 0}, {1, 5, 10}, {1, 2, 3}} Output : 18 (2, 0) ==&gt; (2,
9 min read
Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows : We can only start with arr[i][M] where 0 &lt;= i &lt;= N.We end the path on the same side, such that we can take exactly 2 left turns.First we calcula
2 min read
Minimum cost to reach from the top-left to the bottom-right corner of a matrix
Given an N * M matrix mat[][] consisting of lower case characters, the task is to find the minimum cost to reach from the cell mat[0][0] to the cell mat[N-1][M-1]. If you are at a cell mat[i][j], you can jump to the cells mat[i+1][j], mat[i][j+1], mat[i-1][j], mat[i][j-1] (without going out of bounds) with a cost of 1. Additionally, you can jump to
11 min read
Minimum number of flips required such that a Binary Matrix doesn't contain any path from the top left to the bottom right consisting only of 0s
Given a binary matrix mat[][] of dimensions N*M, the task is to find the minimum number of flips required from the given binary matrix such that there doesn't exist any path from the top-left cell to the bottom-right cell consisting of only 0s. Examples: Input: mat[][] = {{0, 1, 0, 0}, {0, 1, 0, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}}Output: 1Explanation:O
11 min read
Maximize cost to reach the bottom-most row from top-left and top-right corner of given matrix
Given a matrix grid[][] of size M * N where each cell of the matrix denotes the cost to be present on that cell. The task is to maximize the cost of moving to the bottom-most row from top-left and top-right corner of the matrix where in each step: From the cell (i, j) there can be a movement to (i+1, j-1), (i+1, j) or (i+1, j+1).If both the points
15+ min read
Count of possible paths from top left to bottom right of a M x N matrix by moving right, down or diagonally
Given 2 integers M and N, the task is to find the count of all the possible paths from top left to the bottom right of an M x N matrix with the constraints that from each cell you can either move only to right or down or diagonally Examples: Input: M = 3, N = 3Output: 13Explanation: There are 13 paths as follows: VVHH, VHVH, HVVH, DVH, VDH, VHHV, H
14 min read
Lexicographically largest prime path from top-left to bottom-right in a matrix
Given a m x n matrix of positive integers. The task is to find the number of paths from the top left of the matrix to the bottom right of the matrix such that each integer in the path is prime. Also, print the lexicographical largest path among all the path. A cell (a, b) is lexicographical larger than cell (c, d) either a &gt; b or if a == b then
15+ min read
Maximum sum path in a matrix from top-left to bottom-right
Given a matrix mat[][] of dimensions N * M, the task is to find the path from the top-left cell (0, 0) to the bottom-right cell (N - 1, M - 1) of the given matrix such that sum of the elements in the path is maximum. The only moves allowed from any cell (i, j) of the matrix are (i + 1, j) or (i, j + 1). Examples: Input: mat[][] = {{3, 7}, {9, 8}}Ou
12 min read
Maximum non-negative product of a path from top left to bottom right of given Matrix
Given an integer matrix mat[][] of dimensions N * M, the task is to print the maximum product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). If the maximum product is negative, then print "-1". Examples: I
10 min read
Maximum path sum from top left to bottom right of a matrix passing through one of the given cells
Given a matrix mat[][] of dimensions N * M and a set of coordinates of cell coordinates[][] of size Q, the task is to find the maximum sum of a path from the top-left cell (1, 1) to the bottom-right cell (N, M), such that the path should contain at least one of the coordinates from the array coordinates[][2]. The only moves allowed from any cell (i
15 min read
Check if path exists from top-left to bottom-right corner of Grid
Given a grid of dimension M * N where each cell varies from 1 to 6 and each of the values present in the cell represents a path. The task is to check if there exists a path from the top-left corner to the bottom-right corner. The values present in the cell has the following meaning: If the cell value is 1 then it means that there exists a path conn
13 min read
Minimize maximum adjacent difference in a path from top-left to bottom-right
Given a matrix arr[][] of size M * N, where arr[i][j] represents the height of the cell (row, col). The task is to find a path from top-left to bottom-right such that the value of the maximum difference in height between adjacent cells is minimum for that path. Note: A path energy is the maximum absolute difference in heights between two consecutiv
12 min read
Find if path from top-left to bottom-right with sum X exists in given Matrix
Given a matrix A[][] of size N * N, where each matrix element is either -1 or 1. One can move from (X, Y) to either (X + 1, Y) or (X, Y + 1) but not out of the matrix. The task is to check whether a path exists from the top-left to the bottom-right corner such that the sum of all elements in the path is X. Examples: Input: arr[][] = {{1, 1, 1, 1},
13 min read
Shortest path in a Matrix from top-left to bottom right-corner with neighbors exceeding at most K
Given a matrix mat[][] and an integer K, the task is to find the length of the shortest path in a matrix from top-left to bottom right corner such that the difference between neighbor nodes does not exceed K. Example: Input: mat = {{-1, 0, 4, 3}, K = 4, src = {0, 0}, dest = {2, 3} { 6, 5, 7, 8}, { 2, 1, 2, 0}}Output: 7Explanation: The only shortest
15+ min read
Maximum XOR of a path from top-left to bottom-right cell of given Matrix
Given a matrix, mat[][] of dimensions N * M, the task is to print the maximum bitwise XOR value that can be obtained for a path from the top-left cell (0, 0) to the bottom-right cell (N - 1, M - 1) of the given matrix. Only possible moves from any cell (i, j) are (i + 1, j) and (i, j + 1). Note: Bitwise XOR value of a path is defined as the bitwise
9 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.Examples: Input: mat[][] = {{1, 2}, {3, 1}} Output: 0 Explanation: Ev
15+ min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: M = 2, N = 2, mat[M][N] = {{0, 0}, {0, 1}} Output:
12 min read
Minimum steps to convert all top left to bottom right paths in Matrix as palindrome | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: mat[][] = {{1, 2}, {3, 1}}Output: 0Explanation:Ever
9 min read
Intersecting rectangle when bottom-left and top-right corners of two rectangles are given
Given coordinates of 4 points, bottom-left and top-right corners of two rectangles. The task is to find the coordinates of the intersecting rectangle formed by the given two rectangles. Examples: Input: rec1: bottom-left(0, 0), top-right(10, 8), rec2: bottom-left(2, 3), top-right(7, 9) Output: (2, 3) (7, 8) (2, 8) (7, 3) Input: rec1: bottom-left(0,
10 min read
Maximum points from top left of matrix to bottom right and return back
Given a matrix of size N X M consisting of '#', '.' and '*'. '#' means blocked path, '.' means walkable path and '*' means points that you have to collect. Now consider you are at the top left of the matrix. You have to reach the bottom right of the matrix and come back to the top left. When you are moving top left to bottom right, you are allowed
15+ min read
Count of Reachable cells in Grid within given Left-Right moves
Given a grid of size N X M in which some cells are empty, and some have obstacles, the task is to find how many cells (including the starting cell) are reachable from cell (startRow, startCol) such that number of right moves allowed are R and number of left moves allowed are L. An obstacle and empty space are marked as 1 and 0 respectively in the g
12 min read
Minimize count of unique paths from top left to bottom right of a Matrix by placing K 1s
Given two integers N and M where M and N denote a matrix of dimensions N * M consisting of 0's only. The task is to minimize the count of unique paths from the top left (0, 0) to bottom right (N - 1, M - 1) of the matrix across cells consisting of 0's only by placing exactly K 1s in the matrix. Note: Neither the bottom right nor the top-left cell c
10 min read
Minimize flips required to make all shortest paths from top-left to bottom-right of a binary matrix equal to S
Given a binary matrix mat[][] having dimensions N * M and a binary string S of length N + M - 1 , the task is to find the minimum number of flips required to make all shortest paths from the top-left cell to the bottom-right cell equal to the given string S. Examples: Input: mat[][] = [[1, 0, 1, 1], [1, 1, 1, 0]], S = "10010"Output: 3 Explanation:
6 min read
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal
Given an integer N which denotes the size of a matrix, the task is to find the number of possible ways to reach the bottom-right corner from the top-left corner of the matrix without crossing the diagonal of the matrix. The possible movements from any cell (i, j) from the matrix are (i, j + 1) (Right) or (i + 1, j) (Down). Examples: Input: N = 4Out
6 min read
Maximize trailing zeros in product from top left to bottom right of given Matrix
Given a matrix mat[][] of dimensions N * M, the task is to print the maximum number of trailing zeros that can be obtained in the product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). Examples: Input: N =
15+ min read
Bottom-left to upward-right Traversal in a Binary Tree
Given a Binary Tree, the task is to print the Bottom-left to Upward-right Traversal of the given Binary Tree i.e., the level order traversal having level as Bottom-left to Upward-right node. Examples: Input: Below is the given Tree: Output: 2 7 2 5 6 5 11 4 9Explanation: Level 1: 2 7 2 (going upwards from bottom left to right to root) Level 2: 5 6
15 min read
Maximum points by traversing from top left of Matrix to bottom right by two persons
Given a matrix grid[][] of order N*M with numbers 0-9 in the cells. The task is to find the maximum amount of money collected when two persons move from (0, 0) to (N-1, M-1) by moving only right and down. If both persons are at the same cell, then only one of them can pick the money at that location. Examples: Input: 1 1 1 1 0 1 1 1 1Output: 8Expla
7 min read
Minimize the number of turns needed to reach from top left cell to bottom right cell of the matrix.
Given a binary 2D matrix maze[][] of size N X N such that a cell (r, c) is blocked if maze[r][c][/c] = 0 and unblocked if maze[r][c][/c] = 1, the task is to start from cell (0, 0) to reach (N - 1, N - 1) by minimizing the number of turns. We can take any of the four directions (Up, Left, Right, Down) as the starting direction. Then, from each cell,
12 min read
Article Tags :
Practice Tags :