Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph updating algorithm

I have a (un-directed) graph represented using adjacency lists, e.g.

a: b, c, e
b: a, d
c: a, d
d: b, c
e: a

where each node of the graph is linked to a list of other node(s)

I want to update such a graph given some new list(s) for certain node(s), e.g.

a: b, c, d

where a is no longer connected to e, and is connected to a new node d

What would be an efficient (both time and space wise) algorithm for performing such updates to the graph?

like image 592
MLister Avatar asked Jul 22 '12 03:07

MLister


People also ask

Which algorithm is used in graph?

Some Common Graph AlgorithmsBreadth First Search (BFS) Depth First Search (DFS) Dijkstra. Floyd-Warshall Algorithm.

What is graph in advanced algorithm?

A graph is an abstract notation used to represent the connection between pairs of objects. A graph consists of − Vertices − Interconnected objects in a graph are called vertices. Vertices are also known as nodes. Edges − Edges are the links that connect the vertices.

What are graph algorithms good for?

Graph algorithms are used to solve the problems of representing graphs as networks like airline flights, how the Internet is connected, or social network connectivity on Facebook. They are also popular in NLP and machine learning to form networks.

What is the time complexity of graph algorithms?

Time complexity is O(V+E) where V is the number of vertices in the graph and E is number of edges in the graph.


1 Answers

Maybe I'm missing something, but wouldn't it be fastest to use a dictionary (or default dict) of node-labels (strings or numbers) to sets? In this case update could look something like this:

def update(graph, node, edges, undirected=True):
    # graph: dict(str->set(str)), node: str, edges: set(str), undirected: bool
    if undirected:
        for e in graph[node]:
            graph[e].remove(node)
        for e in edges:
            graph[e].add(node)
    graph[node] = edges

Using sets and dicts, adding and removing the node to/from the edges-sets of the other nodes should be O(1), same as updating the edges-set for the node itself, so this should be only O(2n) for the two loops, with n being the average number of edges of a node.

like image 171
tobias_k Avatar answered Sep 29 '22 10:09

tobias_k