C++ program to find out number of changes required to get from one end to other end in a grid

C++Server Side ProgrammingProgramming

Suppose, we are given a grid of dimensions x * y that contains two types of cells, blocked and unblocked. Blocked cells mean that the cells aren't accessible and unblocked means that the cells are accessible. We represent the grid in a 2D array where the blocked cells are given as '#' and the unblocked cells are given as '.'. Now, we have to reach from the cell (0, 0) to cell (x, y). We can perform only two moves, we can either go right of a cell or go down from a cell. We have to keep in mind that, we can only go in unblocked cells, and (0, 0) and (x, y) are both unblocked cells. If we cannot reach (x, y) from (0, 0), we can make a blocked cell an unblocked cell. We have to find the minimum number of changing operations to perform to reach our destination from source.

So, if the input is like x = 4, y = 4, grid = {"..#.", "#.#.", "#.##", "###."}, then the output will be 1.

Only one change operation has to be performed. If we change the cell (2, 2) to unblocked from blocked, then we can reach (3, 3) from (0, 0).

Steps

To solve this, we will follow these steps −

Define one 2D array mat
if grid[0, 0] is same as '#', then:
   mat[0, 0] := 1
Otherwise
   mat[0, 0] := 0
   for initialize i := 0, when i < x, update (increase i by 1), do:
      for initialize j := 0, when j < y, update (increase j by 1), do:
         if i + 1 < x, then:
            mat[i + 1, j] = minimum of (mat[i + 1, j], mat[i, j] + (1 if grid[i + 1, j] is same as '#' AND grid[i, j] is same as '.'))
   if j + 1 < y, then:
mat[i, j + 1] = minimum of (mat[i, j + 1], mat[i, j]+(1 if grid[i, j + 1] is same as '#' AND grid[i, j] is same as '.'))
return mat[x - 1, y - 1]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int x, int y, vector<string> grid){
   vector<vector<int>> mat(x, vector<int>(y, 100));
   if(grid[0][0] == '#')
      mat[0][0] = 1;
   else
      mat[0][0] = 0;
   for(int i = 0; i < x; i++){
      for(int j = 0; j < y; j++){
         if(i + 1 < x){
            mat[i + 1][j] = min(mat[i + 1][j], mat[i][j] + (grid[i + 1][j] == '#' && grid[i][j] == '.'));
         }
         if(j + 1 < y){
            mat[i][j + 1] = min(mat[i][j + 1],mat[i][j]+(grid[i][j + 1] == '#' && grid[i][j] == '.'));
         }
      }
   }
   return mat[x - 1][y - 1];
}
int main() {
   int x = 4, y = 4;
   vector<string> grid = {"..#.", "#.#.", "#.##", "###."};
   cout<< solve(x, y, grid);
   return 0;
}

Input

4, 4, {"..#.", "#.#.", "#.##", "###."}

Output

1
raja
Updated on 02-Mar-2022 12:37:34

Advertisements