A path is a connected sequence of elements from (0,0) to (N-1,N-1), which consists of 1. A sequence of 1s in the 2D array is connected if every 1 in the sequence is adjacent (the above or left neighbour) to the next 1 in the sequence.
For example, in the following matrix:
1 1 0
0 1 1
1 0 1
the 1s marked in blue is a connected path from (0,0) to (2,2). Note that cells at (0,0) and (N-1,N-1) are always 1.
Input
First line consists of the size of the input 2D array N (<=20), following the elements of the matrix, which consist of 0s and 1s in subsequent lines.
Output
Print out the array highlighting the path by red colour if there exists a path between the entry and destination positions, otherwise print out ‘No path has been detected!’.
Note: For a given input matrix with more than a single path, your code only requires detecting and highlighting only one of those paths.
Here is the C++ program for the above problem:-
#include<iostream>
#define N 20
using namespace std;
int maze[N][N] = {
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 1},
{1, 1, 1, 1}
};
int sol[N][N];
void showPath() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << sol[i][j] << " ";
cout << endl;
}
}
bool isValidPlace(int x, int y) {
if(x >= 0 && x < N && y >= 0 && y
< N && maze[x][y] == 1)
return true;
return false;
}
bool path(int x, int y) {
if(x == N-1 && y == N-1) { //when (x,y) is the bottom right
room
sol[x][y] = 1;
return true;
}
if(isValidPlace(x, y) == true) { //check whether (x,y) is valid
or not
sol[x][y] = 1; //set 1, when it is valid place
if (path(x+1, y) == true) //find path by moving right
direction
return true;
if (path(x, y+1) == true) //when x direction is blocked, go for
bottom direction
return true;
sol[x][y] = 0; //if both are closed, there is no path
return false;
}
return false;
}
bool findSolution() {
if(path(0, 0) == false) {
cout << "No path has been detected!";
return false;
}
showPath();
return true;
}
int main() {
findSolution();
}
You are provided a matrix of size N*N with entry position at (0,0) and destination at...