Created
January 10, 2019 18:18
-
-
Save sergeyprokudin/7cf1978964e13802eccdd4df60c902e5 to your computer and use it in GitHub Desktop.
Graph definition as class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GraphNode: | |
def __init__(self, value, neighbors): | |
"""Initialize graph node | |
Parameters | |
---------- | |
name: str | |
node identifier | |
children: list | |
list of child nodes | |
""" | |
self.value = value | |
self.neighbors = neighbors | |
class Graph: | |
def __init__(self, vert_dict): | |
""" | |
Parameters | |
---------- | |
vert_dict: dictionary | |
dictionart containing node ids as keys and node neighbors as values | |
""" | |
self.nodes = {} | |
for v in vert_dict.keys(): | |
self.nodes[v] = GraphNode(v, vert_dict[v]) | |
# Actually, we don't need a special structure to store it! | |
g = {0: [1, 2, 3], 1: [0, 2], 2: [0, 1], 3: [0]} | |
print(Graph(g)) | |
# Another way: as an adjacency matrix | |
g = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0], [1, 0, 0, 0]] | |
# DFS and BFS usage | |
# DFS -> if we need to traverse the graph completely. E.g., if we need to check if there are cycles |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment