Roads and Libraries

  • + 0 comments

    python solution

    # base case when building a lib is cheaper than a road
    if c_lib <= c_road:
        return n*c_lib
    
    # case when have to build roads
    
    # initialize array to keep track of visited cities
        # 'w' not visited
        # 'g' being visited
        # 'b' finished visiting
    visited = ['w'] * (n+1)
    
    # initialize dictionary with all cities as keys
    adj = {}
    for city in range(1, n+1):
        adj[city] = []
    
    # fill in the dictionary by recording adjacencies
    for pair in cities:
        c1 = pair[0]
        c2 = pair[1]
        # record cities as adjacent
        adj[c1].append(c2)
        adj[c2].append(c1)
    
    
    # integer list of components with ints representing their sizes
    components = []
    
    # depth first search
    def dfs(city, count): 
        this_count = 1
        visited[city] = 'g'
        # go through all adjacent cities
        for adjacent in adj[city]:
            # if city has not been visited before 
            if visited[adjacent] == 'w':
                # run dfs on that city
                this_count += dfs(adjacent, count)
        # finished visiting this city
        visited[city] = 'b'
        return this_count
    
    
    for city in range(1, n+1):
        if visited[city] == 'b':
            continue
        count = 0
        count = dfs(city, count)
        components.append(count)
    print(components)
    
    cost = c_lib * len(components)
    for comp in components:
        cost += (comp-1)*c_road
    return cost
    

    '''