Open In App

Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

You are the head of a company with n employees and n distinct jobs to be completed. Every employee takes a different amount of time to complete different jobs, given in the form of a cost[][] matrix, where cost[i][j] represents the time taken by the ith person to complete the jth job. Your task is to assign the jobs in such a way that the total time taken by all employees is minimized.

Note: Each employee must be assigned exactly one job, and each job must be assigned to exactly one employee.

Examples:

Input: n = 4
cost[][] = [ [9, 2, 7, 8],
[6, 4, 3, 7],
[5, 8, 1, 8],
[7, 6, 9, 4] ]
Output: 13
Explanation: Following image depicts the cost associated with each job-worker combinations. Numbers marked in green should be opted to get minimum possible cost.

jobassignment

Input: n = 3
cost[][] = [ [2500, 4000, 3500],
[4000, 6000, 3500],
[2000, 4000, 2500] ]
Output: 9500
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.

Approach:

The idea is to use the Hungarian Algorithm to solve this problem, which works as follows:

  1. For each row, subtract the smallest element from every element in that row.
  2. Repeat the same for each column.
  3. Cover all zeros in the matrix using the minimum number of horizontal and vertical lines.
  4. Test for Optimality:
    • If the number of lines equals N, an optimal assignment exists.
    • If fewer than N, proceed to step 5.
  5. Find the smallest uncovered element, subtract it from all uncovered rows, and add it to all covered columns. Then, return to step 3.

Please refer Hungarian Algorithm for Assignment Problem (Introduction and Implementation) for the detailed explanation and implementation.



Next Article
Article Tags :
Practice Tags :

Similar Reads