Example #1
0
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)  # default_factory() of type list
        self.v = Visualizer()
        self.result = ''

    def add_edge(self, u, v):
        self.graph[u].append(v)
        self.graph[v].append(u)  # Undirected graph is bidrectional
        self.v.add_edge(u, v)

    def visualize(self):
        self.v.visualize()

    def print(self, starting_node):
        print("DFS from vertex {} = {}".format(starting_node, self.result))

    # The function to do DFS traversal. It uses
    # recursive DFSUtil()
    def DFS(self, v):
        '''
        6 starting vertices from 0 to 5
        => bool array with 6 elements
        '''
        visited_arr = [False] * (max(self.graph) + 1)
        '''
        recursive function that takes 
        the index of node and 
        visited array
        '''
        self.DFSUtil(v, visited_arr)

    # Recursive function for DFS with Backtracking
    def DFSUtil(self, v, visited):

        visited[v] = True
        # Adding V to result
        self.result += str(v) + " "

        # Traversing vertices adjacent to this vertex
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
Example #2
0
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)  # default_factory() of type list
        self.v = Visualizer()
        self.result = ""

    def add_edge(self, u, v):
        self.graph[u].append(v)
        self.graph[v].append(u)  # Undirected graph is bidrectional
        self.v.add_edge(u, v)

    # No BFS util required, no recusion required
    # Will be solved with just iteration
    # Passing children of nodes iteratively and visit them
    def BFS(self, starting_node):

        visited_arr = [False] * (len(self.graph))
        queue = list()

        # enqueue it
        queue.append(starting_node)
        visited_arr[starting_node] = True

        while queue:
            node = queue.pop(0)
            self.result += str(node) + " "

            for i in self.graph[node]:
                if visited_arr[i] == False:
                    queue.append(i)
                    visited_arr[i] = True

    def print(self, starting_node):
        print("BFS from vertex {} = {}".format(starting_node, self.result))

    def visualize(self):
        self.v.visualize()