husnain's blog

By husnain, history, 3 days ago, In English

DFS

class graph:
    def __init__(self):
        self.dic = {}
    def add_node(self,a):
        self.dic[a] = []
    def add_edge(self,x,y):
        self.dic[x].append(y)
        self.dic[y].append(x)
    def to(self):
        return self.dic
g = graph()
x = int(input("Enter number of nodes: "))
y = int(input("Enter number of edges: "))
for i in range(x):
    p = input("Enter node: ")
    g.add_node(p)
for i in range(y):
    o,p = input("Enter two nodes which has edge: ").split()
    g.add_edge(o,p)
l = input("Enter starting point: ")
def dfs(visited, graph, node):
    if node not in visited:
        print (node,end = ' ')
        visited.add(node)
        for new in graph[node]:
            dfs(visited, graph, new)
dfs(set(),g.to(),l)

# Author : Husnain Haider

 
 
 
 
  • Vote: I like it
  • -11
  • Vote: I do not like it

»
3 days ago, # |
  Vote: I like it 0 Vote: I do not like it

thanks for sharing dfs code