开发者

Check if there exist a path between two vertices in directed graph acyclic in C++

Given u and v vertices, I want to check if no circuit passes through the edge (u,v) in a directed graph implemented with adjacency list.

here s a brief description of my class :

template <class T>
class Digraph
{
public:
    Digraph();
    ~Digraph();

bool acyclic(T u, T v) const;
int nb_sommets() const;


private:
    std::map<T, std::set<T>> graph;
}

What I tried :

template <class T>
bool Digraph<T>::acyclic(T u, T v) const
{
    // Base case
    if (u == v)
      return true;
 
    // Mark all the vertices as not visited
    bool *visited = new bool[nb_sommets()];
    for (int i = 0; i < nb_sommets(); i++)
        visited[i] = false;
 
    std::list<int> queue;
 
    visited[u] = true;
    queue.push_back(u);
 
    std::list<int>::iterator i;
 
    while (!queue.empty())
    {开发者_运维技巧
        u = queue.front();
        queue.pop_front();
 
        for (i = graph.at(u).begin(); i != graph.at(u).end(); ++i)
        {
            if (*i == v)
                return true;
 
            if (!visited[*i])
            {
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
     
    return false;
}

I have done research to implement the algorithm, however I still get errors. Will someone be kind to help me find the error in my implementation, or can direct me to a solution. thank you !!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜