Program to check whether we can fill square where each row and column will hold distinct elements in Python

Suppose we have one n × n matrix containing values from 0 to n. Here 0 represents an unfilled square, we have to check whether we can fill empty squares such that in each row and each column every number from 1 to n appears exactly once.

This is essentially a Latin square completion problem where we need to verify if a partially filled grid can be completed following sudoku-like rules.

Example Input and Output

So, if the input is like ?

0 0 2
2 0 1
1 2 3

Then the output will be True, as we can set the matrix to ?

3 1 2
2 3 1
1 2 3

Algorithm Steps

To solve this, we will follow these steps ?

  • Find the first empty cell (containing 0) in the matrix

  • If no empty cell exists, check if the matrix is complete and valid

  • For each number from 1 to n, try placing it in the empty cell

  • Check if the placement is feasible (no conflicts in row/column)

  • Recursively solve the remaining matrix

  • Backtrack if no valid solution is found

Implementation

class Solution:
    def solve(self, matrix):
        n = len(matrix)
        
        def find_empty_cell(matrix, n):
            for i in range(n):
                for j in range(n):
                    if matrix[i][j] == 0:
                        return (i, j)
            return (-1, -1)
        
        def is_feasible(matrix, i, j, x):
            # Check if x already exists in row i
            if x in matrix[i]:
                return False
            # Check if x already exists in column j
            if x in [row[j] for row in matrix]:
                return False
            return True
        
        def is_complete(matrix, n):
            # Check if each row contains all numbers 1 to n
            for row in matrix:
                if set(row) != set(range(1, n + 1)):
                    return False
            # Check if each column contains all numbers 1 to n
            for col in range(n):
                if set(row[col] for row in matrix) != set(range(1, n + 1)):
                    return False
            return True
        
        # Find first empty cell
        (i, j) = find_empty_cell(matrix, n)
        
        # If no empty cell found, check completeness
        if (i, j) == (-1, -1):
            if is_complete(matrix, n):
                return True
            else:
                return False
        
        # Try placing numbers 1 to n in the empty cell
        for x in range(1, n + 1):
            if is_feasible(matrix, i, j, x):
                matrix[i][j] = x
                if self.solve(matrix):
                    return True
                matrix[i][j] = 0  # Backtrack
        
        return False

# Test the solution
ob = Solution()
matrix = [
    [0, 0, 2],
    [2, 0, 1],
    [1, 2, 3]
]
print("Can complete the matrix:", ob.solve(matrix))
Can complete the matrix: True

How It Works

The algorithm uses backtracking to systematically try all possible combinations ?

  1. find_empty_cell() ? Locates the first cell containing 0

  2. is_feasible() ? Checks if placing a number violates row/column constraints

  3. is_complete() ? Validates that the filled matrix forms a valid Latin square

  4. solve() ? Main recursive function that tries all possibilities

Testing with Invalid Matrix

# Test with an impossible matrix
ob = Solution()
impossible_matrix = [
    [1, 1, 0],  # Row has duplicate 1s
    [0, 0, 0],
    [0, 0, 0]
]
print("Can complete impossible matrix:", ob.solve(impossible_matrix))
Can complete impossible matrix: False

Time Complexity

The time complexity is O(n^(n²)) in the worst case, where we might try all possible combinations for each empty cell. The space complexity is O(n²) for the recursion stack.

Conclusion

This backtracking solution efficiently determines if a partially filled Latin square can be completed. The algorithm systematically tries all valid placements and backtracks when conflicts arise, ensuring we find a solution if one exists.

Updated on: 2026-03-25T11:16:04+05:30

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements