Here is the solution of the current problem, created by Mr. trincot. The implementation is in C++.
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
const int maximumSize=6;
vector<vector<int>> matrix={{0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0},
{1, 1, 1, 1, 0, 0},
{1, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0}};
vector<vector<int>> visited(maximumSize, vector<int>(maximumSize, 0));
vector<tuple<int, int>> path;
void showContentVector2D(vector<vector<int>>& input)
{
for(int i=0; i<input.size(); ++i)
{
for(int j=0; j<input[i].size(); ++j)
{
cout<<input[i][j]<<", ";
}
cout<<endl;
}
return;
}
void showContentVectorTuple(vector<tuple<int, int>>& input)
{
for(int i=0; i<input.size(); ++i)
{
cout<<get<0>(input[i])<<" : "<<get<1>(input[i])<<endl;
}
return;
}
void dfs(int indexX, int indexY)
{
if(indexX<0 || indexX==matrix.size() || indexY<0 || indexY==matrix[0].size())
{
return;
}
if(indexX==(matrix.size()-1) && (matrix[indexX][indexY]==1))
{
visited[indexX][indexY]=1;
auto indices=make_tuple(indexX, indexY);
path.push_back(indices);
return;
}
visited[indexX][indexY]=1;
auto indices=make_tuple(indexX, indexY);
path.push_back(indices);
if(visited[indexX+1][indexY]==0)
{
if(matrix[indexX+1][indexY]==1)
{
dfs(indexX+1, indexY);
if(visited[indexX+1][indexY])
{
return;
}
}
}
if(visited[indexX-1][indexY]==0)
{
if(matrix[indexX-1][indexY]==1)
{
dfs(indexX-1, indexY);
if(visited[indexX-1][indexY])
{
return;
}
}
}
if(visited[indexX][indexY-1]==0)
{
if(matrix[indexX][indexY-1]==1)
{
dfs(indexX, indexY-1);
if(visited[indexX][indexY-1])
{
return;
}
}
}
if(visited[indexX][indexY+1]==0)
{
if(matrix[indexX][indexY+1]==1)
{
dfs(indexX, indexY+1);
if(visited[indexX][indexY+1])
{
return;
}
}
}
return;
}
void solve()
{
for(int i=0; i<matrix.size(); ++i)
{
if(matrix[0][i]==1)
{
dfs(0, i);
}
}
cout<<"visited <- "<<endl;
showContentVector2D(visited);
cout<<endl<<"matrix <- "<<endl;
showContentVector2D(matrix);
cout<<endl<<"path <- "<<endl;
showContentVectorTuple(path);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Here is the result:
visited <-
0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
1, 1, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0,
matrix <-
0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
0, 1, 0, 1, 0, 0,
1, 1, 1, 1, 0, 0,
1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0,
path <-
0 : 1
1 : 1
2 : 1
3 : 1
3 : 0
4 : 0
5 : 0