maximal_independent_set#
- maximal_independent_set(G, nodes=None, seed=None)[source]#
Returns a random maximal independent set guaranteed to contain a given set of nodes.
An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximal independent set is an independent set such that it is not possible to add a new node and still get an independent set.
- Parameters:
- GNetworkX graph
- nodeslist or iterable
Nodes that must be part of the independent set. This set of nodes must be independent.
- seedinteger, random_state, or None (default)
Indicator of random number generation state. See Randomness.
- Returns:
- indep_nodesset
Set of nodes that are part of a maximal independent set.
- Raises:
- NetworkXUnfeasible
If the nodes in the provided list are not part of the graph or do not form an independent set, an exception is raised.
- NetworkXNotImplemented
If
Gis directed.
See also
maximum_independent_set()Algorithm for approximating the maximum independent set, i.e. a maximal independent set of maximum cardinality.
Notes
This algorithm does not solve the maximum independent set problem.
Examples
>>> G = nx.path_graph(4) >>> sorted(nx.maximal_independent_set(G, seed=1)) [1, 3]
Note that a graph may have many maximal independent sets; for example, the path graph with 4 nodes has 3 maximal independent sets:
{0, 2},{0, 3}and{1, 3}.>>> sorted(nx.maximal_independent_set(G, seed=2)) [0, 2]
This function returns a single maximal independent set. Enumerating all of the maximal independent sets in a graph can be achieved by enumerating the cliques in the complement graph:
>>> sorted( ... sorted(c) ... for c in nx.enumerate_all_cliques(nx.complement(G)) ... if len(c) > 1 # Ignore cliques comprising a single node ... ) [[0, 2], [0, 3], [1, 3]]
Note however that enumerating all cliques is exponential in the number of nodes in the worst case (e.g. the complete graph).
The
nodeskeyword argument can be used to produce a maximal independent set that contains the given node(s):>>> sorted(nx.maximal_independent_set(G, nodes={1})) [1, 3]
An exception is raised if
nodesare not independent>>> nx.maximal_independent_set(G, nodes={1, 2}) Traceback (most recent call last): ... networkx.exception.NetworkXUnfeasible: {1, 2} is not an independent set of G