I know this question has been asked many times in this forum and everywhere else in the internet. But before you attack me with your claws outstretched please bear with me.
I am a newbie learning graph. As part of my excercise I am given to add a method hasCycle() in the Graph class here http://homepage.cs.uiowa.edu/~sriram/21/fall05/ExamplePrograms/ReaderFiles/Chap13/dfs/dfs.java.
My approach, doing a DFS as suggested in this forum here Finding a cycle in an undirected graph vs finding one in a directed graph.
But I am struggling how to implement this using the existing dfs method in the first link.
My approach so far has been:
public boolean hasCycle(int start)
{
vertexList[start].wasVisited = true;
for(int j = 0; j < MAX_VERTS; j++)
{
if(adjMat[start][j]==1 && vertexList[j].wasVisited==true)
return true;
else if(adjMat[start][j]==1 && vertexList[j].wasVisited==false)
{
vertexList[start].wasVisited == true;
hasCycle(j);
}
}
return false;
}
I have two problems here: First I am stuck into an infinite recursion when I call hasCycle() in the DFSApp class instead of the line theGraph.dfs(); Second I am not using the given dfs() as reuired by my homework.
Any direction to the right path would be appreciated in terms of what I am doing wrong here.
For now I am just concentrating on implementing a correct separate hasCycle() method without using dfs().