Hungarian Algorithm
Optimization
Linear Programming
Matrix Covering
Zero Covering Technique

Hungarian Algorithm finding minimum number of lines to cover zeroes?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In the Hungarian algorithm, the step about covering all zeros with the minimum number of horizontal and vertical lines is not a side puzzle. It is the test that tells you whether the current reduced cost matrix already contains enough structure to extract an optimal assignment.

Why Covering Zeros Matters

After row reduction and column reduction, the assignment problem is transformed so that good candidate assignments sit on zero entries. The next question is whether you can choose one zero per row and one zero per column without conflict.

The Hungarian algorithm answers that indirectly:

  • if the minimum number of lines needed to cover all zeros equals n for an n x n matrix, you are ready to build an optimal assignment
  • if fewer than n lines are enough, you must adjust the matrix and continue

This works because of the connection between zero structure, bipartite matching, and minimum vertex cover.

The Graph Interpretation

A reduced matrix can be turned into a bipartite graph:

  • each row becomes a node on the left
  • each column becomes a node on the right
  • every zero entry creates an edge between its row and column

Now the question "minimum number of lines covering all zeros" becomes "minimum number of row and column vertices covering all zero edges."

By Kőnig's theorem, in a bipartite graph the size of a minimum vertex cover equals the size of a maximum matching. That is the theoretical reason the Hungarian algorithm can use zero covering as an optimality test.

Small Example

Suppose the reduced matrix is:

text
0 2 0
0 1 3
4 0 0

The zero positions are:

  • row 0, column 0
  • row 0, column 2
  • row 1, column 0
  • row 2, column 1
  • row 2, column 2

That gives a bipartite graph where rows connect to columns only at those zero positions. If the maximum matching size is 3, then the minimum number of covering lines is also 3, and the matrix is ready for the assignment step. If the maximum matching size is only 2, then you can cover all zeros with two lines, which means the matrix still needs another adjustment.

Practical Hungarian-Algorithm Procedure

Textbook descriptions often explain the line-covering step through marking rules rather than graph theory. A common practical procedure is:

  1. find a maximum set of independent zeros
  2. mark all rows that do not contain an assigned zero
  3. mark every column containing a zero in a marked row
  4. mark every row containing an assigned zero in a marked column
  5. repeat until no new rows or columns can be marked
  6. draw lines through all unmarked rows and all marked columns

The total number of lines you draw is the minimum number needed to cover all zeros.

This marking process is just another way to compute a minimum vertex cover from a maximum matching.

Computing It Programmatically

A clean implementation is to build the zero graph and compute a maximum matching, then derive the cover. The following Python example shows the matching part for a square matrix of zeros and nonzeros.

python
1def max_bipartite_matching(zero_matrix):
2    n = len(zero_matrix)
3    match_to_col = [-1] * n
4
5    def dfs(row, seen):
6        for col in range(n):
7            if zero_matrix[row][col] == 0 and not seen[col]:
8                seen[col] = True
9                if match_to_col[col] == -1 or dfs(match_to_col[col], seen):
10                    match_to_col[col] = row
11                    return True
12        return False
13
14    matched = 0
15    for row in range(n):
16        seen = [False] * n
17        if dfs(row, seen):
18            matched += 1
19
20    return matched, match_to_col
21
22matrix = [
23    [0, 2, 0],
24    [0, 1, 3],
25    [4, 0, 0],
26]
27
28matched, match_to_col = max_bipartite_matching(matrix)
29print("maximum matching size:", matched)
30print("column assignments:", match_to_col)

If matched == n, then the minimum number of covering lines is also n, so the zero pattern is sufficient for an optimal assignment. If matched < n, you continue with the Hungarian adjustment step: subtract the smallest uncovered value from all uncovered elements and add it at intersections of covering lines.

What This Means Inside the Algorithm

The line-cover test does not itself produce the final assignment every time. Its role is to answer whether the current zero structure is rich enough. If not, the matrix must be transformed again to create more useful zeros without changing the true optimum of the original cost problem.

That is why the Hungarian algorithm alternates between:

  • creating or exposing zeros
  • checking whether the zeros support a full assignment

Common Pitfalls

  • Thinking the minimum-line step is separate from matching theory when it is really the same bipartite-cover problem.
  • Covering zeros greedily by sight and assuming the result is always minimal.
  • Forgetting that the number of minimum covering lines is compared with n, the matrix dimension.
  • Confusing "all zeros are covered" with "an optimal assignment is already found."
  • Adjusting the matrix before computing a true minimum cover.

Summary

  • In the Hungarian algorithm, the minimum number of lines covering all zeros is a key optimality test.
  • The zero matrix can be viewed as a bipartite graph of rows, columns, and zero edges.
  • By Kőnig's theorem, the minimum zero cover size equals the maximum matching size.
  • If the minimum cover size is n, the matrix is ready for an optimal assignment.
  • If it is smaller than n, adjust the matrix and repeat the process.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.