Program to find out if the graph is traversable by everybody in Python

In graph theory, we sometimes need to determine if a graph can be traversed by multiple entities with different traversal capabilities. This problem involves finding the minimum number of edges to remove so that both Jack and Casey can traverse the entire graph.

Jack can traverse edges with weight 1, Casey can traverse edges with weight 2, and both can traverse edges with weight 3. We need to ensure both people can reach all vertices by removing the minimum number of edges.

Problem Analysis

The solution uses Union-Find (Disjoint Set Union) data structure to track connected components. We process edges in a specific order:

  • First, process weight-3 edges (usable by both)

  • Then, process weight-1 edges (Jack only)

  • Finally, process weight-2 edges (Casey only)

Implementation

def solve(n, edges):
    def find(val):
        if val != root[val]:
            root[val] = find(root[val])
        return root[val]
    
    def union(val1, val2):
        val1, val2 = find(val1), find(val2)
        if val1 == val2: 
            return 0
        root[val1] = val2
        return 1
    
    res = edge1 = edge2 = 0
    root = list(range(n + 1))
    
    # Process weight-3 edges (both can use)
    for weight, u, v in edges:
        if weight == 3:
            if union(u, v):
                edge1 += 1
                edge2 += 1
            else:
                res += 1
    
    # Save state for Casey's traversal
    root0 = root[:]
    
    # Process weight-1 edges (Jack only)
    for weight, u, v in edges:
        if weight == 1:
            if union(u, v):
                edge1 += 1
            else:
                res += 1
    
    # Restore state and process weight-2 edges (Casey only)
    root = root0
    for weight, u, v in edges:
        if weight == 2:
            if union(u, v):
                edge2 += 1
            else:
                res += 1
    
    return res if edge1 == edge2 == n - 1 else -1

# Test the function
edges = [(3, 2, 3), (1, 0, 1), (2, 1, 2), (1, 3, 4), (2, 4, 0)]
result = solve(5, edges)
print(f"Edges to remove: {result}")
Edges to remove: -1

How It Works

The algorithm follows these key steps:

  1. Union-Find Operations: find() locates the root of a set with path compression, while union() merges two sets

  2. Edge Processing: Weight-3 edges are processed first since both people can use them

  3. Separate Traversals: We simulate Jack's and Casey's traversals separately to ensure both can reach all vertices

  4. Validation: Both people must have exactly n-1 edges in their spanning tree for full connectivity

Example Walkthrough

# Simple example where graph can be made traversable
def simple_example():
    edges = [(3, 0, 1), (3, 1, 2), (1, 2, 3), (2, 3, 4)]
    n = 5
    result = solve(n, edges)
    print(f"Result for simple graph: {result}")

simple_example()
Result for simple graph: 0

Key Points

  • Weight-3 edges are prioritized as they benefit both traversers

  • The algorithm requires exactly n-1 edges for each person's spanning tree

  • Returns -1 if either person cannot traverse the entire graph

  • Uses Union-Find for efficient connected component tracking

Conclusion

This solution efficiently determines if a weighted graph can be made traversable by two entities with different edge weight constraints. The Union-Find approach ensures optimal edge removal while maintaining connectivity for both traversers.

Updated on: 2026-03-26T14:10:57+05:30

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements