I\'m concerned that this might be working on an NP-Complete problem. I\'m hoping someone can give me an answer as to whether it is or not. And I\'m looking for more of an an
Assuming that you have an adjacency matrix:
bool[,] adj = new bool[n, n];
Where bool[i,j] = true if there is an open path between i and j and bool[i,i] = false.
public bool pathExists(int[,] adj, int start, int end)
{
List visited = new List();
List inprocess = new List();
inprocess.Add(start);
while(inprocess.Count > 0)
{
int cur = inprocess[0];
inprocess.RemoveAt(0);
if(cur == end)
return true;
if(visited.Contains(cur))
continue;
visited.Add(cur);
for(int i = 0; i < adj.Length; i++)
if(adj[cur, i] && !visited.Contains(i) && !inprocess.Contains(i))
inprocess.Add(i);
}
return false;
}
Here is a recursive version of the algorithm above (written in Ruby):
def connected? from, to, edges
return true if from == to
return true if edges.include?([from, to])
return true if edges.include?([to, from])
adjacent = edges.find_all { |e| e.include? from }
.flatten
.reject { |e| e == from }
return adjacent.map do |a|
connected? a, to, edges.reject { |e| e.include? from }
end.any?
end