Replacing your for-loop with the below should work:
v = toExplore.peek();
for (int u: getAdjList(v).keySet())
{
if (!visited.contains(u))
{
...
}
}
It seems like the adjacency list contains a mapping of the other vertex index to the edge weight, so the keySet
would give us a list of all the vertices.
Some random notes:
I would recommend a recursive method, if you're allowed. It's a lot simpler once you get your head around recursion (which is definitely a good thing to be comfortable with in the long run). But writing recursive algorithms non-recursively is certainly good programming practice.
As Louis mentioned, making
visited
aSet
(HashSet
) would be much better, if able. This would allow for expectedO(1)
(constant time) lookup, as opposed toO(n)
(linear time).Also, I'd probably make
toExplore
aStack
as you'd only be using stack-based methods.