If the labels are unique, for a graph of size N
, there are O(N^2)
edges, assuming there are no self loops or multiple edges between each pair of vertices. Let's use E
for 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
(with N
vertices) and the possible subgraph G_1
(with M
vertices), and you want to find G_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 have O(M 2^N)
subproblems - one for each vertex in G_1
(with M
vertices) with each of the possible subgraphs.
G_1 is in G = isSubgraph( 0, empty bitmask)
and the states are set up as such:
isSubgraph( index, bitmask ) =
for all vertex in G
if G[vertex] is not used (check bitmask)
and G[vertex]'s label is equal to G_1[index]'s label
and isSubgraph( index + 1, (add vertex to bitmask) )
return true
return false
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 current index
, the current subgraph G_1[0..index]
is equal to G[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).