Checking if a list of strings can be chained

后端 未结 8 792
庸人自扰
庸人自扰 2021-01-31 23:45

Question

Implement a function bool chainable(vector v), which takes a set of strings as parameters and returns true if they

8条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 00:08

    The problem is to check if a Eulerian path exists in the directed graph whose vertices are the letters occurring as first or last letter of at least one of the supplied words and whose edges are the supplied words (each word is the edge from its first letter to its last).

    Some necessary conditions for the existence of Eulerian paths in such graphs:

    1. The graph has to be connected.
    2. All vertices with at most two exceptions have equally many incoming and outgoing edges. If exceptional vertices exist, there are exactly two, one of them has one more outgoing edge than incoming, the other has one more incoming edge than outgoing.

    The necessity is easily seen: If a graph has Eulerian paths, any such path meets all vertices except the isolated vertices (neither outgoing nor incoming edges). By construction, there are no isolated vertices in the graph under consideration here. In a Eulerian path, every time a vertex is visited, except the start and end, one incoming edge and one outgoing edge is used, so each vertex with the possible exception of the starting and ending vertex has equally many incoming and outgoing edges. The starting vertex has one more outgoing edge than incoming and the ending vertex one more incoming edge than outgoing unless the Eulerian path is a cycle, in which case all vertices have equally many incoming and outgoing edges.

    Now the important thing is that these conditions are also sufficient. One can prove that by induction on the number of edges.

    That allows for a very efficient check:

    • record all edges and vertices as obtained from the words
    • use a union find structure/algorithm to count the connected components of the graph
    • record indegree - outdegree for all vertices

    If number of components > 1 or there is (at least) one vertex with |indegree - outdegree| > 1 or there are more than two vertices with indegree != outdegree, the words are not chainable, otherwise they are.

提交回复
热议问题