Im trying to write a method to find whether or not a path exists between to vertex in an undirected graph that is representned in an adjacency matrix.
This is the adjacency matrix that I have:
int[][] adj_matrix ={{0,1,0,0},
{1,0,1,0},
{0,1,0,1},
{0,0,0,0}};
And this is what I have tried so far:
public boolean isPath(int vorigin, int vdestiny)
{
boolean result = false;
ArrayList path = new ArrayList<Integer>();
for (int i = 0; i < adj_matrix.length; i++) {
for (int j = 0; j < adj_matrix.length; j++) {
if(adj_matrix[vorigin][j]>0){
path.add(vorigin);
}
if(adj_matrix[vdestiny][j]>0){
path.add(vdestiny);
break;
}
}
}
if(path.contains(vorigin) && path.contains(vdestiny)){
System.out.println("There is a path");
}
return result;
}
As you can see, my method only check the row where each vertix is located, so it wouldn't be really functional. And I'm on a loss on how to proceed here. I don't really know how to check for the vertex that would indeed be part of the path.
I have been doing quite a bit of research on this, but most of the methods that I have been able to find implement adjacency lists, which is something I dont want to use in this case. And some other methods use recursion, which is a good alternative but I would like to do it on an iterative way. Thanks in advance.
Here is the source code of the Java Program to Find Whether a Path Exists Between 2 Given Nodes. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
Output: