Date: 2026-06-06
Time: 17:29
lucky-numbers-in-a-matrix/solution.pyThis file solves LeetCode 1380 — Lucky Numbers in a Matrix. A "lucky number" is an element that is simultaneously the minimum in its row and the maximum in its column. The file owns both the solution and its inline unit tests.
dfs(matrix: List[List[int]]) -> List[int] — The solver function. Despite the name dfs, this performs no depth-first search; it's a brute-force scan over rows. The naming is a repo-wide convention (all solutions export a function called dfs) rather than a description of the algorithm.
Contract:
m × n matrix of distinct integers.TestDfs — Seven unit tests covering the examples from the problem, plus edge cases for single-element, single-row, single-column, and corner-position lucky numbers.
all() with <=: The column-max check on line 18 uses <= rather than <. This works because the problem states all values are distinct — <= and == behave identically for the candidate value, and strict < for all others.unittest.TestCase directly, gated by if _name == "main". A separate testsolution.py imports dfs for the test harness.Imports: typing.List (type hint), unittest (inline tests).
Imported by: lucky-numbers-in-a-matrix/test_solution.py (and hundreds of other test files import from their respective solution.py — the "Imported By" list in the prompt is the cross-reference for the test runner, not actual imports of *this* file).
1. Iterate over each row in the matrix.
2. Compute min_val = min(row) — the row minimum.
3. Find col = row.index(min_val) — the column index of that minimum.
4. Check if minval is the column maximum by asserting matrix[r][col] <= minval for every row r.
5. If so, append min_val to the result list.
row.index(min_val) call returns the first occurrence, which is the *only* occurrence when values are distinct. If duplicates existed, this could silently pick the wrong column and miss a lucky number.None. Empty matrices would cause min() to raise ValueError, but the problem guarantees m, n >= 1. The function trusts its caller to provide valid input per the LeetCode contract.