Javatpoint Logo
Javatpoint Logo

Hungarian Algorithm Python


You could experience streamlining difficulties much of the time as an information researcher or programming designer who calls for distributing assets to errands in the best manner. One such issue is the task issue, in which we should decide how best to dispense assets to exercises as per their costs or values. One popular methodology for really tackling this issue is the Hungarian calculation. We will look at the Hungarian calculation and set it up as a regular occurrence in Python in this paper.

What is the Assignment Problem?

You might characterize the task issue as follows: We should pick the task that limits the general expense or expands the general worth of the tasks given a bunch of assets and a bunch of errands, where every asset may just be utilized for one undertaking and each assignment just requires one asset. This issue shows up in various regions, including matching issues, work booking, and creation arranging.

The direct task issue represents the need to augment how many assets that might be utilized while limiting how much cash is spent. As an outline, consider the 2D grid displayed beneath, where each line compares to a particular supplier and every segment to the expense of employing that provider to make a specific decent. Every provider is restricted to having some expertise in the formation of only one of these products. For every segment and line in the lattice, just a single component can be picked, and the completion of the chosen things should be limited (limited cost use).

The Hungarian Calculation: An Outline

A powerful strategy that settles the task issue in polynomial time is the Hungarian calculation, some of the time alluded to as the Kuhn-Munkres calculation. To recognize the ideal task, it utilizes a combinatorial enhancement system. The methodology utilizes the "duality" technique to work on the issue and depends on enlarging pathways in a bipartite organization.

The stages utilized by the Hungarian calculation to decide the ideal task are as per the following:

  • Create a cost matrix: Create an expense matrix by building a grid with a line for every asset, a section for each undertaking, and a component for the expense or benefit of utilizing that asset to finish that work.
  • Initialize the assignment matrix: To demonstrate the portion of assets to undertakings, fabricate a second grid with the very aspects of the expense framework that is at first loaded up with zeros.
  • Reduce matrix: To simplify it to distinguish the best task, apply line and segment decreases to the expense network. In this stage, the littlest component in each line and segment should be deducted from any remaining things in the relating column and section, separately.
  • Find the initial feasible solution: Track down the principal useful arrangement by dispensing assets to occupations in a manner that guarantees neither line or segment has more than one task. To do this, define boundaries through the diminished framework's zeros.
  • Augment the assignment: To work on the task, track down the most minimal uncovered component in the decreased framework and deduct it from any remaining uncovered components if the principal answer isn't the most ideal one. Add it to every component covered by two lines after that. Keep doing this until you track down the best task.
  • Improve the assignment: If the task isn't yet great, make changes to the network's lines to open up additional opportunities for way expansion. The former system ought to be rehashed until the ideal task is acquired.
  • Extract the assignment: When the ideal task has been distinguished, eliminate it from the task lattice and give it as the solution to the issue.

Python execution of the Hungarian Calculation

The scipy bundle has a capability called linear_sum_assignment that applies the Hungarian technique to determine the task issue, permitting us to execute the Hungarian calculation in Python. This is a delineation of the way to apply it:

In this illustration, we develop a cost matrix to illustrate the expenses associated with allocating three resources to three tasks. The best assignment is then discovered using the linear_sum_assignment function. The row and column indices of the ideal assignment are contained in the two arrays row_indices and col_indices that the function returns. The assignment is then extracted, and the results are printed.

Given a 2D array, arr of size N*N, where arr[i][j] represents the expense for the ith worker to finish the jth job. Any employee may be tasked with carrying out any task. The goal is to divide up the tasks such that each worker may focus on only one task at a time while minimising the assignment's overall cost.


In this article, many solutions to this issue are described.

Approach: The Hungarian Algorithm will be used to tackle this issue. This is how the algorithm works:

  • Find the smallest element in each row of the matrix and deduct it from each other element in that row.
  • Step 1 should be repeated for each column.
  • Use the fewest possible numbers of horizontal and vertical lines to completely fill the matrix with zeros.
  • Test for Optimality: An optimum assignment is achievable if the least number of covering lines is N. Otherwise, if lines are fewer than N, an optimal assignment is not discovered, and step 5 must be followed.
  • Find the smallest entry that isn't enclosed by a line. This entry is to be subtracted from each uncovered row and added to each covered column. Go back to step 3.

To comprehend the strategy, consider the following example:

Hungarian Algorithm Python

The goal is to utilize the max_cost_assignment() function from the dlib package to construct the aforementioned procedure. The Hungarian algorithm, sometimes referred to as the Kuhn-Munkres algorithm, is implemented in this function and takes O(N^3) time to complete. The problem of the ideal assignment is resolved.

The application of the aforementioned strategy is seen below:



Time Complexity: O(N^3)

Auxiliary Space: O(N^2)


The Hungarian strategy is a successful method for expediently settling the task issue. The calculation decides the best task by using expanding pathways in a bipartite organization to limit costs or boost values. Here, the Hungarian technique was analyzed, and the scipy bundle was utilized to carry out it in Python. As an information researcher or programmer, you may now utilize this skill to involve the Hungarian calculation to handle schoolwork issues in your own undertakings.

The Hungarian strategy is just one of the various advancement calculations open; prior to choosing the best calculation for a given circumstance, understanding the constraints and issue context is fundamental.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA