Example #1
0
def hamiltonian_cycles(graph):
    count = 0

    for subset in subsets(graph.vertices()):
        count += (-1)**len(subset) * closed_walks(graph, subset)

    return int(count / (2 * graph.vertex_count()))
Example #2
0
def perfect_matchings(graph):
    if graph.vertex_count() % 2 != 0:
        return 0

    count = 0

    for subset in subsets(graph.vertices()):
        count += (-1)**len(subset) * edge_sets(graph, subset)

    return int(count)
def count_indepset(rows, cols):
    graph = make_grid(rows, cols)
    decomp = grid_decomp(rows, cols)
    table = [{} for t in range(len(decomp))]

    for t, node in enumerate(decomp):
        for s in map(frozenset, subsets(node['bag'])):
            if node['type'] == 'leaf':
                table[t][s] = 1
            elif node['type'] == 'introduce':
                if node['v'] not in s:
                    table[t][s] = table[t - 1][s]
                elif any([graph.edge_exists(u, node["v"]) for u in s]):
                    table[t][s] = 0
                else:
                    table[t][s] = table[t - 1][s - {node["v"]}]
            elif node['type'] == 'forget':
                v = node["v"]
                table[t][s] = table[t - 1][s] + table[t - 1][s.union({v})]

    return sum(table[-1].values())
Example #4
0
def tsp_dp(start, g):
    vts = frozenset(g.vertices())
    table = {frozenset(sub): {v: inf for v in vts} for sub in subsets(vts)}
    table[frozenset([start])][start] = 0

    for k in range(1, g.vertex_count() + 1):
        for subset in map(frozenset, combinations(vts, k)):
            for v in subset:
                reduced = subset - frozenset([v])
                for u in filter(lambda u: g.edge_exists(u, v), vts):
                    table[subset][v] = min(
                        table[subset][v],
                        table[reduced][u] + g.edge_weight(u, v))

    cycle = [start]

    while len(vts) > 0:
        u = cycle[-1]
        v = min(g.adjacent(u),
                key=lambda v: table[vts][v] + g.edge_weight(v, u))
        cycle.append(v)
        vts -= {v}

    return cycle
Example #5
0
def brute_isets(g: Graph) -> List[Tuple[int]]:
    """Uses brute force to construct all independent sets of g"""
    return [s for s in subsets(g.vertices()) if gh.is_iset(g, s)]
Example #6
0
def brute_vc(g: Graph) -> int:
    """Computes the size of the minimum vertex cover of g using brute force"""
    return min([len(sub) for sub in subsets(g.vertices()) if gh.is_vc(g, sub)])