// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
class Solution {
int bfs(vector<vector<int> >& matrix, int& x, int& y)
{
if (matrix[x][y] == 0)
return -1;
// Queue for bfs traversal
queue<vector<int> > q;
int n = matrix.size(), m = matrix[0].size();
q.push({ x, y, 0 });
int ans = -1;
vector<vector<int> > visited(n, vector<int>(m, 0));
while (q.size()) {
vector<int> v = q.front();
int i = v[0], j = v[1], moves = v[2];
q.pop();
if (i >= n || i < 0 || j >= m || j < 0) {
// As soon as p reaches
// out of the bounds stop
// bfs calls
ans = moves;
break;
}
else {
if (visited[i][j])
continue;
visited[i][j] = 1;
// Bfs calls in all
// possible directions
if (i + 1 >= n || matrix[i + 1][j])
q.push({ i + 1, j, moves + 1 });
if (i - 1 < 0 || matrix[i - 1][j])
q.push({ i - 1, j, moves + 1 });
if (j + 1 >= m || matrix[i][j + 1])
q.push({ i, j + 1, moves + 1 });
if (j - 1 < 0 || matrix[i][j - 1])
q.push({ i, j - 1, moves + 1 });
}
}
return ans;
}
public:
int minMoves(vector<vector<int> >& matrix, int x, int y)
{
int ans = bfs(matrix, x, y);
return (ans >= 1e7) ? -1 : ans - 1;
}
};
// Driver code
int main()
{
vector<vector<int> > matrix = { { 0, 1, 0, 0, 0 },
{ 0, 1, 1, 0, 0 },
{ 0, 1, 1, 1, 0 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 1, 0 } };
int x = 1, y = 2;
Solution obj;
// Function call
cout << obj.minMoves(matrix, x, y) << endl;
return 0;
}