简体   繁体   中英

Alternate(s) to making adjaceny list in python with dictionary for graph problems? (like vector<vector<int>> in c++)

In python I've noticed people make graphs using defaultdict(list) or something of that nature. How do you write list<int> adj[n] or vector<vector<int>> adj(n) in python?

Won't using dictionaries which are basically unordered_maps make the run time slow on large graphs?

Using the OOPs way! Taken from Graphs and it's representations . Thanks to @DarrylG for providing it!

# A class to represent the adjacency list of the node 
class AdjNode: 
    def __init__(self, data): 
        self.vertex = data 
        self.next = None


# A class to represent a graph. A graph 
# is the list of the adjacency lists. 
# Size of the array will be the no. of the 
# vertices "V" 
class Graph: 
    def __init__(self, vertices): 
        self.V = vertices 
        self.graph = [None] * self.V 

    # Function to add an edge in an undirected graph 
    def add_edge(self, src, dest): 
        # Adding the node to the source node 
        node = AdjNode(dest) 
        node.next = self.graph[src] 
        self.graph[src] = node 

        # Adding the source node to the destination as 
        # it is the undirected graph 
        node = AdjNode(src) 
        node.next = self.graph[dest] 
        self.graph[dest] = node 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM