0

Assume a std::set< std::pair<char, char> >, can somebody suggest an algorithm or approach to check whether there are cyclic pairs?

e.g.

std::set< std::pair<char, char> > cyclic = { {'A', 'B'}, {'B', 'C'}, {'C', 'A'} };
std::set< std::pair<char, char> > not_cyclic = { {'A', 'B'}, {'B', 'C'}, {'C', 'C'} };

isCyclic(cyclic);     // true
isCyclic(not_cyclic); // false

I don't want to use any extern library (c++ library is allowed), since the function bool isCyclic(const std::set< std::pair<char, char> >& set); will only be used once and it should be overkill to #include a big library like boost just for that one function...

Any ideas how to tackle this problem?

user2804578
  • 32
  • 1
  • 4

1 Answers1

0

What you have here is a graph, characters being its vertices and pairs in the set - the edges. You can detect whether there is a cycle easily using any search for instance BFS or DFS. Also have a look at this question. Don't mind that it deals with undirected case as the algorithm is the same.

Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176