What you're doing is called graph traversal. Check out Dijkstra's Algorithm, it's probably the most straight-forward graph traversal.
http://math.mit.edu/~rothvoss/18.304.3PM/Presentations/1-Melissa.pdf
Question
I am trying to search through a map of sorts. There are Town objects and Path objects. The Towns are connected to the Paths via Town names. So for instance, if you have the name of a town, and you have a name of the second town, you can see if they make a path. Players can control the paths, and if they do, the path turns their color.
I want to recursively search the paths to see if I have a connection from one Town to another via paths. I have included a picture with what I am trying to do. The start is the start parameter, and end is the end. The double lines are the paths that I control, and have my color attached to them.
How the code is written right now, I will get stuck in that second town because it will find that it is a path owned by me and will mark it as visited. I know I have to backtrack in some way but I'm not sure how I would go about it.
public boolean continuousPath(Town start, Town end)
{
//search for towns with the same name
//as the starting town
for(Path p : paths)
{
if(p.getStartTown().equals(start))
{
matches.add(p); //add it to an arraylist of matches
}
}
//for the matches arrayList
for(Path pa: matches)
{
if(pa.getEndTown().equals(end)){
matches.clear();
return true;
}
else{
if(!alreadyVisited(r)){
if(p.getPlayerColor().equals(colorArray[playerTurn]))
{
visited.add(r);
matches.clear();
Town tempTown = r.getEndTown();
continuousPath(tempTown, end);
}
}
}
}
return false;
}
public boolean alreadyVisited(Path p)
{
for(Path pathInstance : visited){
if(p.getName().equals(pathInstance.getName()))
{
return true;
}
}
return false;
}
Picture of what I'm trying to do:
Solution
What you're doing is called graph traversal. Check out Dijkstra's Algorithm, it's probably the most straight-forward graph traversal.
http://math.mit.edu/~rothvoss/18.304.3PM/Presentations/1-Melissa.pdf