def DFS(graph, s, explored): stack = [s] explored.append(s) #print "Explored: " + str(explored) while stack: v = stack.pop() for w in graph[v]: if w not in explored: explored.append(w) #print "Explored: " + str(explored) stack.append(w) return explored def rec_DFS(graph, s, expl): expl.append(s) for w in graph[s]: if w not in expl: rec_DFS(graph, w, expl) return expl def find_all_components(G): exp = [] num_of_components = 0 for v in G: if v not in exp: DFS(G, v, exp) num_of_components += 1 return num_of_components graph = {'s': ['a', 'b'], 'a': ['s', 'c'], 'b': ['s', 'c', 'd'], 'c': ['a', 'b', 'd', 'e'], 'd': ['b', 'c', 'e'], 'e': ['c', 'd']} graph1 = {'1': ['3', '5'], '2': ['4'], '3': ['1', '5'], '4': ['2'], '5': ['1', '3' ,'7', '9'], '6': ['8', '10'], '7': ['5'], '8': ['6', '10'], '9': ['5'], '10': ['6', '8']} print "normal DFS " + str(DFS(graph, 's', [])) print "recursive DFS " + str(rec_DFS(graph, 's', [])) print "Numer of components: " + str(find_all_components(graph1))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question