Python Program to find out the determinant of a given special matrix

Determinants of special matrices formed from tree structures have important applications in graph theory and computational mathematics. In this problem, we construct an n×n matrix A where each element A(x,y) equals the weight of the least common ancestor (LCA) of vertices x and y in a tree.

Problem Understanding

Given a tree with n vertices labeled 1 to n, where vertex 1 is the root and each vertex has weight wi, we need to find the determinant of matrix A where A(x,y) = weight_of_LCA(x,y).

Example Tree Structure

For input edges [[1, 2], [1, 3], [1, 4], [1, 5]] with weights [1, 2, 3, 4, 5], the tree looks like:

1 2 3 4 5 Root (1) with weight 1, children with weights [2,3,4,5]

Matrix Formation

The resulting matrix A where A(i,j) is the weight of LCA of vertices i and j:

1 2 3 4 5
1 1 1 1 1 1
2 1 2 1 1 1
3 1 1 3 1 1
4 1 1 1 4 1
5 1 1 1 1 5

Algorithm Approach

The algorithm uses a depth-first traversal to compute the determinant efficiently using the matrix tree theorem property ?

  1. Build adjacency list: Store tree structure with weights
  2. Stack-based traversal: Process each vertex with parent weight
  3. Determinant calculation: Multiply (vertex_weight - parent_weight) for each vertex

Implementation

def solve(input_array, weights, vertices):
    # Build adjacency list with weights
    w = [[weights[i], []] for i in range(vertices)]
    
    # Add edges to adjacency list
    for i, item in enumerate(input_array):
        p, q = item[0], item[1]
        w[p - 1][1].append(q - 1)
        w[q - 1][1].append(p - 1)
    
    det = 1
    stack = [(0, 0)]  # (vertex_index, parent_weight)
    
    while stack:
        i, parent_weights = stack.pop()
        # Multiply determinant by (vertex_weight - parent_weight)
        det = (det * (w[i][0] - parent_weights)) % (10**9 + 7)
        
        # Add children to stack with current vertex weight
        stack += [(t, w[i][0]) for t in w[i][1]]
        
        # Remove processed vertex from children's adjacency lists
        for t in w[i][1]:
            w[t][1].remove(i)
    
    return det

# Test the function
result = solve([[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5)
print("Determinant:", result)
Determinant: 24

How It Works

For the given example:

  • Root (vertex 1): (1 - 0) = 1
  • Vertex 2: (2 - 1) = 1
  • Vertex 3: (3 - 1) = 2
  • Vertex 4: (4 - 1) = 3
  • Vertex 5: (5 - 1) = 4

Final determinant = 1 × 1 × 2 × 3 × 4 = 24

Conclusion

This algorithm efficiently computes the determinant of special tree-based matrices using the matrix tree theorem. The time complexity is O(n) where n is the number of vertices, making it suitable for large tree structures.

Updated on: 2026-03-25T20:29:38+05:30

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements