bundles / scipy 1.17.1 / scipy / sparse / csgraph / _matching / maximum_bipartite_matching
cython_function_or_method
scipy.sparse.csgraph._matching:maximum_bipartite_matching
Signature
def maximum_bipartite_matching ( graph , perm_type = row ) Summary
Returns a matching of a bipartite graph whose cardinality is at least that of any given matching of the graph.
Parameters
graph: sparse array or matrixInput sparse in CSR format whose rows represent one partition of the graph and whose columns represent the other partition. An edge between two vertices is indicated by the corresponding entry in the matrix existing in its sparse representation.
perm_type: str, {'row', 'column'}Which partition to return the matching in terms of: If
'row', the function produces an array whose length is the number of columns in the input, and whose 'th element is the row matched to the 'th column. Conversely, ifperm_typeis'column', this returns the columns matched to each row.
Returns
perm: ndarrayA matching of the vertices in one of the two partitions. Unmatched vertices are represented by a
-1in the result.
Notes
This function implements the Hopcroft--Karp algorithm [1]. Its time complexity is , and its space complexity is linear in the number of rows. In practice, this asymmetry between rows and columns means that it can be more efficient to transpose the input if it contains more columns than rows.
By Konig's theorem, the cardinality of the matching is also the number of vertices appearing in a minimum vertex cover of the graph.
Note that if the sparse representation contains explicit zeros, these are still counted as edges.
The implementation was changed in SciPy 1.4.0 to allow matching of general bipartite graphs, where previous versions would assume that a perfect matching existed. As such, code written against 1.4.0 will not necessarily work on older versions.
If multiple valid solutions are possible, output may vary with SciPy and Python version.
Examples
from scipy.sparse import csr_array from scipy.sparse.csgraph import maximum_bipartite_matching✓
graph = csr_array([[0, 0, 1], [1, 1, 0]])
✓print(maximum_bipartite_matching(graph, perm_type='column')) print(maximum_bipartite_matching(graph, perm_type='row'))✓
data = [0, 0, 0] indices = [2, 0, 1] indptr = [0, 1, 3] graph = csr_array((data, indices, indptr)) print(maximum_bipartite_matching(graph, perm_type='column')) print(maximum_bipartite_matching(graph, perm_type='row'))✓
graph = csr_array((2, 0)) print(maximum_bipartite_matching(graph, perm_type='column')) print(maximum_bipartite_matching(graph, perm_type='row'))✓
a = [[0, 1, 2, 0], [1, 0, 0, 1], [2, 0, 0, 3], [0, 1, 3, 0]] graph = csr_array(a) perm = maximum_bipartite_matching(graph, perm_type='row') print(graph[perm].toarray())✓
Aliases
-
scipy.sparse.csgraph.maximum_bipartite_matching