How to determine if two nodes are connected?

前端 未结 11 1183
清酒与你
清酒与你 2020-12-09 03:31

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

11条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 04:07

    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
    

提交回复
热议问题