- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Divide & Conquer

Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Merge Sort Algorithm
- Bubble Sort Algorithm
- Tree Traversals (Inorder, Preorder and Postorder)
- Binary Search
- Arrays in Java
- Insertion Sort
- Selection Sort Algorithm
- What is Linked List
- Breadth First Search or BFS for a Graph
- Insertion in Linked List
- Depth First Search or DFS for a Graph
- Dijkstra's Shortest Path Algorithm | Greedy Algo-7
- Program for Fibonacci numbers
- Binary Search Tree | Set 1 (Search and Insertion)
- Reverse a Linked List
- Write a program to reverse an array or string
- 0/1 Knapsack Problem
- Largest Sum Contiguous Subarray (Kadane's Algorithm)
- Arrays in C/C++
- std::sort() in C++ STL
- Bitwise Operators in C/C++
- Program for array left rotation by d positions.
- Top 50 Array Coding Problems for Interviews
- Introduction to Stack - Data Structure and Algorithm Tutorials
- Reverse a string in Java
- Graph and its representations
- Prim’s Algorithm for Minimum Spanning Tree (MST)
- Practice for Cracking Any Coding Interview
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)
- Difficulty Level : Expert
- Last Updated : 20 Jul, 2021
Given a 2D array , arr of size N*N where arr[i][j] denotes the cost to complete the j th job by the i th worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized.
Input: arr[][] = {{3, 5}, {10, 1}} Output: 4 Explanation: The optimal assignment is to assign job 1 to the 1st worker, job 2 to the 2nd worker. Hence, the optimal cost is 3 + 1 = 4. Input: arr[][] = {{2500, 4000, 3500}, {4000, 6000, 3500}, {2000, 4000, 2500}} Output: 4 Explanation: The optimal assignment is to assign job 2 to the 1st worker, job 3 to the 2nd worker and job 1 to the 3rd worker. Hence, the optimal cost is 4000 + 3500 + 2000 = 9500.
Different approaches to solve this problem are discussed in this article .
Approach: The idea is to use the Hungarian Algorithm to solve this problem. The algorithm is as follows:
- For each row of the matrix, find the smallest element and subtract it from every element in its row.
- Repeat the step 1 for all columns.
- Cover all zeros in the matrix using the minimum number of horizontal and vertical lines.
- Test for Optimality : If the minimum number of covering lines is N , an optimal assignment is possible. Else if lines are lesser than N , an optimal assignment is not found and must proceed to step 5.
- Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3.
Consider an example to understand the approach:
Let the 2D array be: 2500 4000 3500 4000 6000 3500 2000 4000 2500 Step 1: Subtract minimum of every row. 2500, 3500 and 2000 are subtracted from rows 1, 2 and 3 respectively. 0 1500 1000 500 2500 0 0 2000 500 Step 2: Subtract minimum of every column. 0, 1500 and 0 are subtracted from columns 1, 2 and 3 respectively. 0 0 1000 500 1000 0 0 500 500 Step 3: Cover all zeroes with minimum number of horizontal and vertical lines. Step 4: Since we need 3 lines to cover all zeroes, the optimal assignment is found. 2500 4000 3500 4000 6000 3500 2000 4000 2500 So the optimal cost is 4000 + 3500 + 2000 = 9500
For implementing the above algorithm, the idea is to use the max_cost_assignment() function defined in the dlib library . This function is an implementation of the Hungarian algorithm (also known as the Kuhn-Munkres algorithm) which runs in O(N 3 ) time. It solves the optimal assignment problem.
Below is the implementation of the above approach:
Time Complexity: O(N 3 ) Auxiliary Space: O(N 2 )
Solve DSA problems on GfG Practice.
Please Login to comment...
Prepare for Google & other Product Based Companies
In JAVA/C++ Language
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.
- No suggested jump to results
- Notifications
Python 3 implementation of the Hungarian Algorithm
benchaplin/hungarian-algorithm
Name already in use.
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more .
- Open with GitHub Desktop
- Download ZIP
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Hungarian algorithm.
A Python 3 graph implementation of the Hungarian Algorithm (a.k.a. the Kuhn-Munkres algorithm), an O(n^3) solution for the assignment problem , or maximum/minimum-weighted bipartite matching problem .
The function find_matching takes 3 inputs:
- G = the bipartite graph (a dictionary of dictionaries*)
- matching_type = 'max' or 'min' (maximum-weighted matching or minimum-weighted matching)
- return_type = 'list' or 'total' (return a list of matched vertices and weights or the total weight*)
*See examples below.
Example 1 (maximum-weighted matching)
Suppose you're choosing 11 starting positions for a soccer team.
The 11 players submit their top 3 position choices, and it is your job to create the optimal team.
The situation can be modeled with a weighted bipartite graph :

Then, if you assign weight 3 to blue edges, weight 2 to red edges and weight 1 to green edges, your job is simply to find the matching that maximizes total weight. This is the assignment problem , for which the Hungarian Algorithm offers a solution.
Notice: although no one has chosen LB, the algorithm will still assign a player there. In fact, the first step of the algorithm is to create a complete bipartite graph (all possible edges exist), giving new edges weight 0.
Define a weighted bipartite graph in the following manner:
thus defining a complete bipartite graph G = (L ∪ R, E) with:
- Vertex set L (Players) = {'Ann', 'Ben', 'Cal', 'Dan', 'Ela', 'Fae', 'Gio', 'Hol', 'Ian', 'Jon', 'Kay'}
- Vertex set R (Positions) = {'GK', 'LB', 'SWP', 'CB', 'RB', 'LW', 'CM', 'CAM', 'RW', 'F', 'S'}
- Edge set E = { e = (Player, Position) : for all Players, for all Positions}
- w( Player , Position ) = 3 for a first choice
- w( Player , Position ) = 2 for a second choice
- w( Player , Position ) = 1 for a third choice
- w( Player , Position ) = 0 otherwise
Then pass the graph as an input:
You will get the output:
If you only need the total weight:
Example 2 (minimum-weighted matching)
Suppose you manage a group of drivers delivering packages to various locations.
You estimate the time of delivery for each driver to deliver each package, and it is your job to save the most time.
This time, we will model the situation with a matrix:

where the values in the matrix give the number of minutes it would take each driver to deliver each package. Again, this is the assignment problem , except this time we seek to find a minimum-weighted matching to minimize the total amount of delivery time.
Then pass the graph as an input (this time, remember to change matching_type = 'min' to find a minimum-weighted matching):
The algorithm was published by Harold Kuhn in 1955 paper The Hungarian Method for the Assignment Problem . Kuhn's work relied heavily on that of Hungarian mathematicians Dénes Kőnig and Jenő Egévary.
Contributors 2
- Python 100.0%

Hungarian Algorithm Introduction & Python Implementation
How to use hungarian method to resolve the linear assignment problem..
By Eason on August 2nd, 2021
In this article, I will introduce how to use Hungarian Method to resolve the linear assignment problem and provide my personal Python code solution.
So… What is the linear assignment problem?
The linear assignment problem represents the need to maximize the available resources (or minimize the expenditure) with limited resources. For instance, below is a 2D matrix, where each row represents a different supplier, and each column represents the cost of employing them to produce a particular product. Each supplier can only specialize in the production of one of these products. In other words, only one element can be selected for each column and row in the matrix, and the sum of the selected elements must be minimized (minimized cost expense).
The cost of producing different goods by different producers:
Indeed, this is a simple example. By trying out the possible combinations, we can see that the smallest sum is 13, so supplier A supplies Bubble Tea , supplier B supplies milk tea, and supplier C supplies Fruit Tea . However, such attempts do not follow a clear rule and become inefficient when applied to large tasks. Therefore, the next section will introduce step by step the Hungarian algorithm, which can be applied to the linear assignment problem.
Hungarian Algorithm & Python Code Step by Step
In this section, we will show how to use the Hungarian algorithm to solve linear assignment problems and find the minimum combinations in the matrix. Of course, the Hungarian algorithm can also be used to find the maximum combination.
Step 0. Prepare Operations
First, an N by N matrix is generated to be used for the Hungarian algorithm (Here, we use a 5 by 5 square matrix as an example).
The above code randomly generates a 5x5 cost matrix of integers between 0 and 10.
If we want to find the maximum sum, we could do the opposite. The matrix to be solved is regarded as the profit matrix, and the maximum value in the matrix is set as the common price of all goods. The cost matrix is obtained by subtracting the profit matrix from the maximum value. Finally, the cost matrix is substituted into the Hungarian algorithm to obtain the minimized combination and then remapped back to the profit matrix to obtain the maximized sum value and composition result.
The above code randomly generates a 5x5 profit matrix of integers between 0 and 10 and generate a corresponding cost matrix
By following the steps above, you can randomly generate either the cost matrix or the profit matrix. Next, we will move into the introduction of the Hungarian algorithm, and for the sake of illustration, the following sections will be illustrated using the cost matrix shown below. We will use the Hungarian algorithm to solve the linear assignment problem of the cost matrix and find the corresponding minimum sum.
Example cost matrix:
Step 1. Every column and every row subtract its internal minimum
First, every column and every row must subtract its internal minimum. After subtracting the minimum, the cost matrix will look like this.
Cost matrix after step 1:
And the current code is like this:
Step 2.1. Min_zero_row Function Implementation
At first, we need to find the row with the fewest zero elements. So, we can convert the previous matrix to the boolean matrix(0 → True, Others → False).
Transform matrix to boolean matrix:
Corresponding Boolean matrix:
Therefore, we can use the “min_zero_row” function to find the corresponding row.
The row which contains the least 0:

Third, mark any 0 elements on the corresponding row and clean up its row and column (converts elements on the Boolean matrix to False). The coordinates of the element are stored in mark_zero.
Hence, the boolean matrix will look like this:
The boolean matrix after the first process. The fourth row has been changed to all False.
The process is repeated several times until the elements in the boolean matrix are all False. The below picture shows the order in which they are marked.
The possible answer composition:

Step 2.2. Mark_matrix Function Implementation
After getting Zero_mat from the step 2–1, we can check it and mark the matrix according to certain rules. The whole rule can be broken down into several steps:
- Mark rows that do not contain marked 0 elements and store row indexes in the non_marked_row
- Search non_marked_row element, and find out if there are any unmarked 0 elements in the corresponding column
- Store the column indexes in the marked_cols
- Compare the column indexes stored in marked_zero and marked_cols
- If a matching column index exists, the corresponding row_index is saved to non_marked_rows
- Next, the row indexes that are not in non_marked_row are stored in marked_rows
Finally, the whole mark_matrx function is finished and then returns marked_zero , marked_rows , marked_cols. At this point, we will be able to decide the result based on the return information.
If we use the example cost matrix, the corresponding marked_zero , marked_rows, and marked_cols are as follows:
- marked_zero : [(3, 2), (0, 4), (1, 1), (2, 0), (4, 3)]
- marked_rows : [0, 1, 2, 3, 4]
- marked_cols : []
Step 3. Identify the Result
At this step, if the sum of the lengths of marked_rows and marked_cols is equal to the length of the cost matrix, it means that the solution of the linear assignment problem has been found successfully, and marked_zero stores the solution coordinates. Fortunately, in the example matrix, we find the answer on the first try. Therefore, we can skip to step 5 and calculate the solution.
However, everything is hardly plain sailing. Most of the time, we will not find the solution on the first try, such as the following matrix:
After Step 1 & 2 , the corresponding matrix, marked_rows, and marked_cols are as follows:

The sum of the lengths of Marked_Rows and Marked_Cols is 4 (less than 5).
Apparently, the sum of the lengths is less than the length of the matrix. At this time, we need to go into Step 4 to adjust the matrix.
Step 4. Adjust Matrix
In Step 4, we're going to put the matrix after Step 1 into the Adjust_Matrix function . Taking the latter matrix in Step 3 as an example, the matrix to be modified in Adjust_Matrix is:
The whole function can be separated into three steps:
- Find the minimum value for an element that is not in marked_rows and not in marked_cols . Hence, we can find the minimum value is 1.

- Subtract the elements which not in marked_rows nor marked_cols from the minimum values obtained in the previous step.

- Add the element in marked_rows , which is also in marked_cols , to the minimum value obtained by Step 4–1.

Return the adjusted matrix and repeat Step 2 and Step 3 until the conditions satisfy the requirement of entering Step 5.
Step 5. Calculate the Answer
Using the element composition stored in marked_zero , the minimum and maximum values of the linear assignment problem can be calculated.

The minimum composition of the assigned matrix and the minimum sum is 18.

The maximum composition of the assigned matrix and the maximum sum is 43.
The code of the Answer_Calculator function is as follows:
The complete code is as follows:
Hungarian algorithm - Wikipedia
Continue Learning
27 javascript data visualization libraries for 2022.
Libraries for beautiful charts, graphs, and data visualization for your JS applications.
Creating a Chrome Extension with React
The potential of virtual reality in healthcare, 6 best react data visualization libraries.
Level Up Your React Projects in No Time
Create a Product Rating System with MongoDB and Node.js
3 ways to store data in the browser.
Cookies, local storage, and session storage


Oct 12, 2020
The Assignment Problem (Using Hungarian Algorithm)
Ever encountered a problem where you wanted to divide work among people such that you do it in the most optimal way? Then this problem is just for you. The assignment problem assigns tasks to agents in the most optimal way! Read on ahead to know about the Assignment Problem and how to solve it using the “ Hungarian Algorithm ”.
What is the Assignment Problem?
Let there be n agents and n tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task and exactly one task to each agent in such a way that the total cost of the assignment is minimized. We need to ensure the following things:
- The number of assignments and agents should be the same.
- Each agent should be assigned only one job and every job should be assigned only one agent
- We want to find the feasible solution which will consume the minimum cost
Problem: In a construction site there are 4 cranes. Each crane must be allocated to one job. The time required for each job for each crane is shown in the table below. Find the best assignment of cranes to the jobs so that the time required to finish the jobs is minimum.
Applications of the Assignment Problem
Few applications of the Assignment Problem are:
- Assigning machines to factory orders.
- Assigning sales/marketing people to territories.
- Assigning teachers to classes.
- Assigning police vehicles to patrolling areas.
Few Approaches to solve the Assignment Problem
- Approach 1: Brute Force Here we try all the combinations one by one to find the optimal solution. This is a tedious approach because as the number of tasks and cranes go on increasing , the number of calculations also increase. The complexity is n! which is very inefficient.
- Approach 2: Graph Approach The algorithm is easier to describe if we formulate the problem using a bipartite graph. We have a complete bipartite graph G=(S, T; E) with n worker vertices S and n job vertices (T), and each edge has a nonnegative cost c(i,j). We want to find a perfect matching with a minimum total cost.
- Approach 3: Greedy Approach In this case, the algorithm will choose the lowest cost worker to be assigned to the task as the first assignment, then choose the next lowest cost worker to be assigned to the task, and so on until all tasks have been assigned. The algorithm repeats this procedure until all workers have at least one task. Greedy algorithms try to get close to the optimal solution by improving a candidate solution iteratively, with no guarantee that an optimal solution will actually be found.
- Approach 4: Hungarian Algorithm The Hungarian Algorithm is a combinatorial optimization algorithm which is a faster approach which solves the problem in polynomial time complexity. We see the Hungarian approach ahead.
The Hungarian Algorithm
1.Find the minimum element from each row and substract that value from all the elements of the row.
2. Find the minimum element from each column and substract that value from all the elements of the column.
3. Let m=minimum number of lines required to cover all the zeroes in the table
4. while(m!=number of row/columns)
- Find the minimum element from the uncovered elements
- Substract this element from all the other uncovered elements
- Add this element to the elements where the lines are intersecting
5. Use the zeroes to assign possible combinations- i.e wherever there is a zero present, task can be assigned.
6. Find the minimum cost
Solving an Example Using Hungarian Problem
We use the previous problem statement (in the example mentioned above) and solve that problem using Hungarian Algorithm.
STEP 1: Finding the minimum from each row and substracting it from all the other row elements
STEP 2: Finding the minimum from each column and substracting it from all the other column elements
STEP 3: Finding the minimum number of lines required to cover all the zeroes
As we can see that when we draw lines on column 1 and 2 and row 3, all the zeroes of the table are covered but this is not equal to the number of rows and columns.
STEP 4.i.ii.iii: Finding the minimum element from the uncovered elements and substract it from the rest of the uncovered elements and adding it to the intersecting elements.
Step 4.iv. Finding the minimum number of lines required to cover all the zeroes.
Now we see that upon drawing the lines on Row 1, Row 2 and Column 2, all the zeroes are covered. But still the number of lines(m) is not equal to the number of rows/columns(n) and so we repeat step 4 again.
Step 4.i.ii.iii. Finding the minimum from the uncovered elements, substracting it from the rest of the uncovered elements and adding that element to the elements where lines are intersecting.
Now we see that on drawing vertical lines on row 1, row 2, row 3, row 4 we have covered all the zeroes in minimum number of lines. Now our number of lines(m)=number of rows/columns(n)=4 and so we have reached an optimal solution.
Step 5: Use the zeroes to assign possible combinations- wherever there is a zero present, task can be assigned to respective agent and job.
Step 6: Find the cost.
When we use the previous tables assignments of the jobs and cranes, we calculate the cost by adding the costs of the individual assignment. The minimum cost comes out to be 19 which tallies with the solution we got in the previous example. Hence we have arrived at the solution.
Note: If we assume the other combinations, we will still get the same answer of minimum value. The other combinations using the zeroes in the table obtained in 4(iv) gives us the same minimum cost.
Hope after reading this blog your concepts about the Assignment Problem and Hungarian Algorithm are clear!
Credits: The example used in this blog has been taken from the following YouTube video — https://www.youtube.com/watch?v=ezSx8OyBZVc . The problem statement is taken from — https://www.geeksforgeeks.org/hungarian-algorithm-assignment-problem-set-1-introduction/
More from Riya Tendulkar
Coding Enthusiast
About Help Terms Privacy
Get the Medium app

Riya Tendulkar
Text to speech

- Submissions
P_Nyagolov's blog
Implementing Hungarian Algorithm
Hello everybody,
A while ago I decided to learn about Hungarian algorithm. After watching some videos and reading some articles I think I got the main idea:
1) Find the minimum number in each row and subtract it from all elements in the row.
2) Find the minimum number in each column and subtract it from all elements in the column.
3) Cover all zeroes with minimum number of vertical and/or horizontal lines.
4) If the number of the lines is N, then we have found our assignment. Otherwise, find the minimum uncovered number, subtract it from all uncovered numbers and then go back to step 3.
Well, the thing is that I never found a good implementation. I can implement step 1 and 2. For step 3, I think that we can check whether the minimum number of lines is equal to N using bipartite matching. But if the minimum number is less than N, I don't know how I can find those covering lines. Please, help me with implementing it.
Thanks in advance!

- File Exchange
- Community Home
- MATLAB Answers
- Communities
- Treasure Hunt
- Virtual Badges
- Followed Content Feed
- Manage Following
- Communication Preferences
- Trial software
You are now following this Submission
- You may receive emails, depending on your communication preferences


Hungarian Algorithm for Linear Assignment Problems (V2.3)
16.7K Downloads All time: 16,695">
Updated 15 Sep 2011
View License
- Version History
- Reviews (35)
- Discussions (25)
This is an extremely fast implementation of the famous Hungarian algorithm (aslo known as Munkres' algorithm). It can solve a 1000 x 1000 problem in about 20 seconds in a Core Duo (T2500 @ 2.00GHz) XP laptop with Matlab 2008a, which is about 2.5 times faster than the mex code "assignmentoptimal" in FEX ID 6543, about 6 times faster than the author's first version in FEX ID 20328, and at least 30 times faster than other Matlab implementations in the FEX.
The code can also handle rectangular prolems and problems with forbiden allocations.
The new version (V2.3)is able to conduct a partial assignment if a full assignment is not feasible.
For more details of the Hungarian algorithm, visit http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
Yi Cao (2023). Hungarian Algorithm for Linear Assignment Problems (V2.3) (https://www.mathworks.com/matlabcentral/fileexchange/20652-hungarian-algorithm-for-linear-assignment-problems-v2-3), MATLAB Central File Exchange. Retrieved March 9, 2023 .
MATLAB Release Compatibility
Platform compatibility.
- Mathematics and Optimization > Global Optimization Toolbox > Particle Swarm >
Tags Add Tags
Acknowledgements.
Inspired by: assignprob.zip , Functions for the rectangular assignment problem , Munkres Assignment Algorithm
Inspired: Hungarian Algorithm for Linear Sum Assignment Problem , Minimum Cost Constrained Input-Output and Control Configuration Co-Design Problem , Eigenshuffle , LAPJV - Jonker-Volgenant Algorithm for Linear Assignment Problem V3.0 , Hungarian based particle linking , simpletracker , Smooth Point-set Registration using Neighboring Constraints , TACTICS Toolbox
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
Learn About Live Editor
- munkres(costMat)
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
- Switzerland (English)
- Switzerland (Deutsch)
- Switzerland (Français)
- 中国 (English)
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
- América Latina (Español)
- Canada (English)
- United States (English)
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 简体中文 Chinese
- 日本 Japanese (日本語)
- 한국 Korean (한국어)
Contact your local office
Stack Exchange Network
Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Computational Science Stack Exchange is a question and answer site for scientists using computers to solve scientific problems. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Looking for a C/C++ implementation of the Hungarian method for real-valued cost matrix
I am looking for a C/C++ implementation of the Hungarian method for solving the linear assignment problem with real-valued cost matrix.
Some implementation I found, such as this one , only work for integer costs :(
Any suggestions are very appreciated!
Thank you in advance!
- optimization
- combinatorics
- 1 $\begingroup$ Wouldn't it work to multiply your cost by a big constant and take the integer part of it ? so that you could directly use the link mentioned in the question, at the expense of loosing a little bit of precision, if you can afford it. $\endgroup$ – BrunoLevy Nov 7, 2015 at 10:15
- $\begingroup$ Go to CRAN and download the "clue" package source . The LSAP code contains a C implementation of the Hungarian method. $\endgroup$ – Biswajit Banerjee Nov 7, 2015 at 19:36
This one seems to work great for me:
https://github.com/mcximing/hungarian-algorithm-cpp
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged optimization c++ combinatorics or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
Hot Network Questions
- Protect public project from potential patents
- Annoying color lines in table
- Does every US state set its standard deduction to match the federal one? Why?
- Go through a building and not die trying
- Why do amsmath and \char interact in this way?
- Are there any known methods for a Mage to strengthen their avatar?
- Why study a classical language?
- Why was the Sanskrit word "laksha" anglicized to "lakh"?
- how does the key signature work (not reading it)
- How can I sharpen oscillating tool blades?
- The consultancy company that offered me a job has delayed my start date twice (by a total of 12 weeks so far)
- Running a computational calculation from Python
- Can you be issued a trespass warning on public property for no reason at all?
- Why would a plane opt out of flying through a class bravo?
- Is it ok to say "When we would go to a restaurant ......." instead of "When we went to a restaurant, ....."?
- EXPLAIN ANALYZE does not show what takes time with my GIN index scan
- EventBus in C++
- Will a whole house surge protector save energy?
- "Sort" by element duplication
- Options for "Cancel this operation?" are "Cancel" and "Yes"; what would be better wording for customers in a hurry?
- Did courtiers of antiquity hold in their pee or did they have common commodes available in the king/queen's court?
- Is there any possibility of obtaining an asymptotic approximation (instead of numerical solutions) of such a 2nd-order homogeneous ODE in Mathematica?
- Compensation for train journey rerouting due to track-work (Sweden–Germany)?
- If G is an almost simple group, then Aut(G) is complete?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Hungarian Method
The Hungarian method is a computational optimization technique that addresses the assignment problem in polynomial time and foreshadows following primal-dual alternatives. In 1955, Harold Kuhn used the term “Hungarian method” to honour two Hungarian mathematicians, Dénes Kőnig and Jenő Egerváry. Let’s go through the steps of the Hungarian method with the help of a solved example.
Hungarian Method to Solve Assignment Problems
The Hungarian method is a simple way to solve assignment problems. Let us first discuss the assignment problems before moving on to learning the Hungarian method.
What is an Assignment Problem?
A transportation problem is a type of assignment problem. The goal is to allocate an equal amount of resources to the same number of activities. As a result, the overall cost of allocation is minimised or the total profit is maximised.
Because available resources such as workers, machines, and other resources have varying degrees of efficiency for executing different activities, and hence the cost, profit, or loss of conducting such activities varies.
Assume we have ‘n’ jobs to do on ‘m’ machines (i.e., one job to one machine). Our goal is to assign jobs to machines for the least amount of money possible (or maximum profit). Based on the notion that each machine can accomplish each task, but at variable levels of efficiency.
Hungarian Method Steps
Check to see if the number of rows and columns are equal; if they are, the assignment problem is considered to be balanced. Then go to step 1. If it is not balanced, it should be balanced before the algorithm is applied.
Step 1 – In the given cost matrix, subtract the least cost element of each row from all the entries in that row. Make sure that each row has at least one zero.
Step 2 – In the resultant cost matrix produced in step 1, subtract the least cost element in each column from all the components in that column, ensuring that each column contains at least one zero.
Step 3 – Assign zeros
- Analyse the rows one by one until you find a row with precisely one unmarked zero. Encircle this lonely unmarked zero and assign it a task. All other zeros in the column of this circular zero should be crossed out because they will not be used in any future assignments. Continue in this manner until you’ve gone through all of the rows.
- Examine the columns one by one until you find one with precisely one unmarked zero. Encircle this single unmarked zero and cross any other zero in its row to make an assignment to it. Continue until you’ve gone through all of the columns.
Step 4 – Perform the Optimal Test
- The present assignment is optimal if each row and column has exactly one encircled zero.
- The present assignment is not optimal if at least one row or column is missing an assignment (i.e., if at least one row or column is missing one encircled zero). Continue to step 5. Subtract the least cost element from all the entries in each column of the final cost matrix created in step 1 and ensure that each column has at least one zero.
Step 5 – Draw the least number of straight lines to cover all of the zeros as follows:
(a) Highlight the rows that aren’t assigned.
(b) Label the columns with zeros in marked rows (if they haven’t already been marked).
(c) Highlight the rows that have assignments in indicated columns (if they haven’t previously been marked).
(d) Continue with (b) and (c) until no further marking is needed.
(f) Simply draw the lines through all rows and columns that are not marked. If the number of these lines equals the order of the matrix, then the solution is optimal; otherwise, it is not.
Step 6 – Find the lowest cost factor that is not covered by the straight lines. Subtract this least-cost component from all the uncovered elements and add it to all the elements that are at the intersection of these straight lines, but leave the rest of the elements alone.
Step 7 – Continue with steps 1 – 6 until you’ve found the highest suitable assignment.
Hungarian Method Example
Use the Hungarian method to solve the given assignment problem stated in the table. The entries in the matrix represent each man’s processing time in hours.
\(\begin{array}{l}\begin{bmatrix} & I & II & III & IV & V \\1 & 20 & 15 & 18 & 20 & 25 \\2 & 18 & 20 & 12 & 14 & 15 \\3 & 21 & 23 & 25 & 27 & 25 \\4 & 17 & 18 & 21 & 23 & 20 \\5 & 18 & 18 & 16 & 19 & 20 \\\end{bmatrix}\end{array} \)
With 5 jobs and 5 men, the stated problem is balanced.
\(\begin{array}{l}A = \begin{bmatrix}20 & 15 & 18 & 20 & 25 \\18 & 20 & 12 & 14 & 15 \\21 & 23 & 25 & 27 & 25 \\17 & 18 & 21 & 23 & 20 \\18 & 18 & 16 & 19 & 20 \\\end{bmatrix}\end{array} \)
Subtract the lowest cost element in each row from all of the elements in the given cost matrix’s row. Make sure that each row has at least one zero.
\(\begin{array}{l}A = \begin{bmatrix}5 & 0 & 3 & 5 & 10 \\6 & 8 & 0 & 2 & 3 \\0 & 2 & 4 & 6 & 4 \\0 & 1 & 4 & 6 & 3 \\2 & 2 & 0 & 3 & 4 \\\end{bmatrix}\end{array} \)
Subtract the least cost element in each Column from all of the components in the given cost matrix’s Column. Check to see if each column has at least one zero.
\(\begin{array}{l}A = \begin{bmatrix}5 & 0 & 3 & 3 & 7 \\6 & 8 & 0 & 0 & 0 \\0 & 2 & 4 & 4 & 1 \\0 & 1 & 4 & 4 & 0 \\2 & 2 & 0 & 1 & 1 \\\end{bmatrix}\end{array} \)
When the zeros are assigned, we get the following:

The present assignment is optimal because each row and column contain precisely one encircled zero.
Where 1 to II, 2 to IV, 3 to I, 4 to V, and 5 to III are the best assignments.
Hence, z = 15 + 14 + 21 + 20 + 16 = 86 hours is the optimal time.
Practice Question on Hungarian Method
Use the Hungarian method to solve the following assignment problem shown in table. The matrix entries represent the time it takes for each job to be processed by each machine in hours.
\(\begin{array}{l}\begin{bmatrix}J/M & I & II & III & IV & V \\1 & 9 & 22 & 58 & 11 & 19 \\2 & 43 & 78 & 72 & 50 & 63 \\3 & 41 & 28 & 91 & 37 & 45 \\4 & 74 & 42 & 27 & 49 & 39 \\5 & 36 & 11 & 57 & 22 & 25 \\\end{bmatrix}\end{array} \)
Stay tuned to BYJU’S – The Learning App and download the app to explore all Maths-related topics.
Frequently Asked Questions on Hungarian Method
What is hungarian method.
The Hungarian method is defined as a combinatorial optimization technique that solves the assignment problems in polynomial time and foreshadowed subsequent primal–dual approaches.
What are the steps involved in Hungarian method?
The following is a quick overview of the Hungarian method: Step 1: Subtract the row minima. Step 2: Subtract the column minimums. Step 3: Use a limited number of lines to cover all zeros. Step 4: Add some more zeros to the equation.
What is the purpose of the Hungarian method?
When workers are assigned to certain activities based on cost, the Hungarian method is beneficial for identifying minimum costs.
Leave a Comment Cancel reply
Your Mobile number and Email id will not be published. Required fields are marked *
Request OTP on Voice Call
Post Comment

- Share Share
Register with BYJU'S & Download Free PDFs


We're sorry, this computer has been flagged for suspicious activity.
If you are a member, we ask that you confirm your identity by entering in your email.
You will then be sent a link via email to verify your account.
If you are not a member or are having any other problems, please contact customer support.
Thank you for your cooperation

Index Assignment problem Hungarian algorithm Solve online
The Hungarian algorithm: An example
We consider an example where four jobs (J1, J2, J3, and J4) need to be executed by four workers (W1, W2, W3, and W4), one job per worker. The matrix below shows the cost of assigning a certain worker to a certain job. The objective is to minimize the total cost of the assignment.
Below we will explain the Hungarian algorithm using this example. Note that a general description of the algorithm can be found here .
Step 1: Subtract row minima
We start with subtracting the row minimum from each row. The smallest element in the first row is, for example, 69. Therefore, we substract 69 from each element in the first row. The resulting matrix is:
Step 2: Subtract column minima
Similarly, we subtract the column minimum from each column, giving the following matrix:
Step 3: Cover all zeros with a minimum number of lines
We will now determine the minimum number of lines (horizontal or vertical) that are required to cover all zeros in the matrix. All zeros can be covered using 3 lines:
Step 4: Create additional zeros
First, we find that the smallest uncovered number is 6. We subtract this number from all uncovered elements and add it to all elements that are covered twice. This results in the following matrix:
Now we return to Step 3.
Again, We determine the minimum number of lines required to cover all zeros in the matrix. Now there are 4 lines required:
Because the number of lines required (4) equals the size of the matrix ( n =4), an optimal assignment exists among the zeros in the matrix. Therefore, the algorithm stops.
The optimal assignment
The following zeros cover an optimal assignment:
This corresponds to the following optimal assignment in the original cost matrix:
Thus, worker 1 should perform job 3, worker 2 job 2, worker 3 job 1, and worker 4 should perform job 4. The total cost of this optimal assignment is to 69 + 37 + 11 + 23 = 140.
Solve your own problem online

HungarianAlgorithm.com © 2013-2023
HungarianAlgorithm.com uses cookies to provide you with an optimal user experience.
Yes, I accept cookies.
hungarian-algorithm 0.1.11
pip install hungarian-algorithm Copy PIP instructions
Released: May 24, 2020
Python 3 implementation of the Hungarian Algorithm for the assignment problem.
Project links
- Open issues:
View statistics for this project via Libraries.io , or by using our public dataset on Google BigQuery
License: MIT License
Author: Ben Chaplin
Maintainers
Classifiers
- OSI Approved :: MIT License
- OS Independent
- Python :: 3
Project description
Hungarian algorithm.
A Python 3 graph implementation of the Hungarian Algorithm (a.k.a. the Kuhn-Munkres algorithm), an O(n^3) solution for the assignment problem , or maximum/minimum-weighted bipartite matching problem .
The function find_matching takes 3 inputs:
- G = the bipartite graph (a dictionary of dictionaries*)
- matching_type = 'max' or 'min' (maximum-weighted matching or minimum-weighted matching)
- return_type = 'list' or 'total' (return a list of matched vertices and weights or the total weight*)
*See examples below.
Example 1 (maximum-weighted matching)
Suppose you're choosing 11 starting positions for a soccer team.
The 11 players submit their top 3 position choices, and it is your job to create the optimal team.
The situation can be modeled with a weighted bipartite graph :
Then, if you assign weight 3 to blue edges, weight 2 to red edges and weight 1 to green edges, your job is simply to find the matching that maximizes total weight. This is the assignment problem , for which the Hungarian Algorithm offers a solution.
Notice: although no one has chosen LB, the algorithm will still assign a player there. In fact, the first step of the algorithm is to create a complete bipartite graph (all possible edges exist), giving new edges weight 0.
Define a weighted bipartite graph in the following manner:
thus defining a complete bipartite graph G = (L ∪ R, E) with:
- Vertex set L (Players) = {'Ann', 'Ben', 'Cal', 'Dan', 'Ela', 'Fae', 'Gio', 'Hol', 'Ian', 'Jon', 'Kay'}
- Vertex set R (Positions) = {'GK', 'LB', 'SWP', 'CB', 'RB', 'LW', 'CM', 'CAM', 'RW', 'F', 'S'}
- Edge set E = { e = (Player, Position) : for all Players, for all Positions}
- w( Player , Position ) = 3 for a first choice
- w( Player , Position ) = 2 for a second choice
- w( Player , Position ) = 1 for a third choice
- w( Player , Position ) = 0 otherwise
Then pass the graph as an input:
You will get the output:
If you only need the total weight:
Example 2 (minimum-weighted matching)
Suppose you manage a group of drivers delivering packages to various locations.
You estimate the time of delivery for each driver to deliver each package, and it is your job to save the most time.
This time, we will model the situation with a matrix:
where the values in the matrix give the number of minutes it would take each driver to deliver each package. Again, this is the assignment problem , except this time we seek to find a minimum-weighted matching to minimize the total amount of delivery time.
Then pass the graph as an input (this time, remember to change matching_type = 'min' to find a minimum-weighted matching):
The algorithm was published by Harold Kuhn in 1955 paper The Hungarian Method for the Assignment Problem . Kuhn's work relied heavily on that of Hungarian mathematicians Dénes Kőnig and Jenő Egévary.
Project details
Release history release notifications | rss feed.
May 24, 2020
Apr 29, 2020
Apr 13, 2020
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages .
Source Distribution
Uploaded May 24, 2020 source
Built Distribution
Uploaded May 24, 2020 py3
Hashes for hungarian_algorithm-0.1.11.tar.gz
Hashes for hungarian_algorithm-0.1.11-py3-none-any.whl.
- português (Brasil)
Supported by

IMAGES
VIDEO
COMMENTS
The Hungarian Method: The following algorithm applies the above theorem to a given n × n cost matrix to find an optimal assignment. Step 1. Subtract the smallest entry in each row from all the entries of its row. Step 2. Subtract the smallest entry in each column from all the entries of its column. Step 3.
The Hungarian algorithm, aka Munkres assignment algorithm, utilizes the following theorem for polynomial runtime complexity ( worst case O (n3)) and guaranteed optimality: If a number is added to or subtracted from all of the entries of any one row or column of a cost matrix, then an optimal assignment for the resulting cost matrix is also an …
This function is an implementation of the Hungarian algorithm (also known as the Kuhn-Munkres algorithm) which runs in O (N3) time. It solves the optimal assignment problem. Below is the implementation of the above approach: Python import dlib def minCost (arr): assignment = dlib.max_cost_assignment (arr)
Hungarian Algorithm The Hungarian algorithm is a combinatorial optimization method, that solves the assignment problem in polynomial time, and which anticipated later primal-dual methods.
The Hungarian method is a combinatorial optimization algorithm that solves the assignment problem in polynomial time and which anticipated later primal-dual methods.
This is the assignment problem, for which the Hungarian Algorithm offers a solution. Notice: although no one has chosen LB, the algorithm will still assign a player there. In fact, the first step of the algorithm is to create a complete bipartite graph (all possible edges exist), giving new edges weight 0. Define a weighted bipartite graph in ...
We will use the Hungarian algorithm to solve the linear assignment problem of the cost matrix and find the corresponding minimum sum. Example cost matrix: view raw cost_matrix.csv hosted with by GitHub Step 1. Every column and every row subtract its internal minimum First, every column and every row must subtract its internal minimum.
The Assignment Problem (Using Hungarian Algorithm) | by Riya Tendulkar | Medium Write Sign up Sign In 500 Apologies, but something went wrong on our end. Refresh the page, check Medium 's...
1) Find the minimum number in each row and subtract it from all elements in the row. 2) Find the minimum number in each column and subtract it from all elements in the column. 3) Cover all zeroes with minimum number of vertical and/or horizontal lines. 4) If the number of the lines is N, then we have found our assignment.
The assignment problem is a special case of the transportation problem, which in turn is a special case of the min-cost flow problem, so it can be solved using algorithms that solve the more general cases. Also, our problem is a special case of binary integer linear programming problem (which is NP-hard).
Hungarian Algorithm for Linear Assignment Problems (V2.3) Version 1.4.0.0 (3.27 KB) by Yi Cao An extremely fast implementation of the Hungarian algorithm on a native Matlab code. 4.5 (35) 16.7K Downloads Updated 15 Sep 2011 View License Download Overview Functions Version History Reviews (35) Discussions (25)
I am looking for a C/C++ implementation of the Hungarian method for solving the linear assignment problem with real-valued cost matrix. Some implementation I found, such as this one, only work for ... The LSAP code contains a C implementation of the Hungarian method. $\endgroup$ - Biswajit Banerjee. Nov 7, 2015 at 19:36.
How to Solve an Assignment Problem Using the Hungarian Method Shokoufeh Mirzaei 15.3K subscribers Subscribe 182K views 5 years ago Linear Programming In this lesson we learn what is an...
The Hungarian method is a computational optimization technique that addresses the assignment problem in polynomial time and foreshadows following primal-dual alternatives. In 1955, Harold Kuhn used the term "Hungarian method" to honour two Hungarian mathematicians, Dénes Kőnig and Jenő Egerváry. Let's go through the steps of the Hungarian method with the help of a solved example.
Hungarian Algorithm Application. First, we want to turn our matrix into a square matrix by adding a dummy column with entries equal to 518 (the highest entry in the matrix). Now we have a 4 by 4 ...
Assignment Problem | Hungarian Method | Example of Assignment Problem | Operation Research | नियतन समस्या | assignment problem in operation research | minimi...
An Assignment Problem solved using the Hungarian Algorithm - HungarianAlgorithm.com The Hungarian algorithm: An example We consider an example where four jobs (J1, J2, J3, and J4) need to be executed by four workers (W1, W2, W3, and W4), one job per worker. The matrix below shows the cost of assigning a certain worker to a certain job.
Hungarian Algorithm A Python 3 graph implementation of the Hungarian Algorithm (a.k.a. the Kuhn-Munkres algorithm), an O (n^3) solution for the assignment problem, or maximum/minimum-weighted bipartite matching problem. Usage Install pip3 install hungarian-algorithm Import from hungarian_algorithm import algorithm Inputs
It is shown that ideas latent in the work of two Hungarian mathematicians may be exploited to yield a new method of solving this problem. Citing Literature Volume 2 , Issue 1-2