Given a Boolean 2D matrix (0-based index), find whether there is a path from (0,0) to (x,y) and if there is one path, print the minimum no of steps needed to reach it, else print -1 if the destination is not reachable
belongs to collection: interview C++ coding problems/challenges | Matrix
All Answers
total answers (1)

C++ programming
Pre-requisites:
1. Defining a point in the maze
We need to define a "point" class having two data attributes 1) row no and 2) column no
class point{ public: int row; int column; };2. Defining node used in solution
A concept of node is used in the solution which actually is an object with two data attributes
class node{ public: point p; int d; };Algorithm:
Mark the node visited.
EnQueue its neighbour nodes if unvisited
Print -1.
Since we have use BFS traversal technique it's guaranteed to reach the destination node in minimum no of steps if the destination is reachable from the source node. (point (0, 0)).
So the steps are:
Check whether point (0,0) is 0 or not.
If it's 0, then we can't make any path from here, so to print -1 & return.
Initially all nodes are unvisited
Finding neighbour nodes
All the directions are marked on basis of the current index.
Checking valid node
If (row of current point<0) Out of matrix; If (column of current point<0) Out of matrix; If (row of current point>=m) //m is row no of matrix Out of matrix; If (column of current point>=n) //n is column no of matrix Out of matrix;C++ implementation
Output
need an explanation for this answer? contact us directly to get an explanation for this answer