Check for possible path in 2D matrix in C++


Consider we have a 2D array. We have to find if we can get a path from topleft corner to bottom-right corner. The matrix is filled with 0s and 1s. 0 indicates open area, 1 indicates blockage. Note that the top-left corner will always be 1.

Suppose a matrix is like below −

00010
10011
00010
10000
00100

One path is marked as green, there are some other paths also. So the program will return true, if there is a path, otherwise false.

We will solve this problem, by changing all accessible node to -1, First change the value of starting point to -1, then get next value in the first row, and compare to the previous value, set the current value equal to previous value iff it is reachable (not 0). Do the same for the column values also. By comparing and setting the current with the previous column values if that is reachable. Then starting from first row, first column, and take the values of previous row, previous column, get minimum between them. And set current index into the minimum. If the current index is 1, then there is no change. At the end if the final index is same as the bottom-right, then return true, otherwise false.

Example

 Live Demo

#include <iostream>
#define row 5
#define col 5
using namespace std;
bool isPathPresent(int arr[row][col]) {
   arr[0][0] = -1;
   for (int i = 1; i < row; i++)
      if (arr[i][0] != 1)
         arr[i][0] = arr[i - 1][0];
   for (int j = 1; j < col; j++)
      if (arr[0][j] != 1)
         arr[0][j] = arr[0][j - 1];
   for (int i = 1; i < row; i++)
      for (int j = 1; j < col; j++)
         if (arr[i][j] != 1)
            arr[i][j] = min(arr[i][j - 1], arr[i - 1][j]);
   return (arr[row - 1][col - 1] == -1);
}
int main() {
   int arr[row][col] = {{ 0, 0, 0, 1, 0},
      {1, 0, 0, 1, 1},
      { 0, 0, 0, 1, 0},
      {1, 0, 0, 0, 0},
      { 0, 0, 1, 0, 0}};
   if (isPathPresent(arr))
      cout << "Path is present";
   else
      cout << "No path has found";
}

Output

Path is present

Updated on: 21-Oct-2019

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements