I’m looking for an algorithm to check whether a given graph is subgraph of another given graph.
I have few conditions to make this NP complete problem bit more feasible..
- The graphs have approx <20 vertices.
- The graphs are DAG.
- All vertices are non-uniquely labeled, and the corresponding vertices in the main graph and the subgraph should have same label. I don’t know if I’m using the correct terminologies (because I haven’t taken a graph theory course…). It will be something like:
The line graph A–B is subgraph of A–B–A but A–A is not a subgraph of A–B–A.
Any suggestions are fine. This is not a homework question btw. 😀
If the labels are unique, for a graph of size
N, there areO(N^2)edges, assuming there are no self loops or multiple edges between each pair of vertices. Let’s useEfor the number of edges.If you hash the set edges in the parent graph, you can go through the subgraph’s edges, checking if each one is in the hash table (and in the correct amount, if desired). You’re doing this once for each edge, therefore,
O(E).Let’s call the graph
G(withNvertices) and the possible subgraphG_1(withMvertices), and you want to findG_1 is in G.Since the labels are not unique, you can, with Dynamic Programming, build the subproblems as such instead – instead of having
O(2^N)subproblems, one for each subgraph, you haveO(M 2^N)subproblems – one for each vertex inG_1(withMvertices) with each of the possible subgraphs.G_1 is in G = isSubgraph( 0, empty bitmask)and the states are set up as such:
with the base case being
index = M, and you can check for the edges equality, given the bitmask (and an implicit label-mapping). Alternatively, you can also do the checking within the if statement – just check that given currentindex, the current subgraphG_1[0..index]is equal toG[bitmask](with the same implicit label mapping) before recursing.For
N = 20, this should be fast enough.(add your memo, or you can rewrite this using bottoms up DP).