-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphSearch.py
87 lines (78 loc) · 2.12 KB
/
GraphSearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python2
# -*- coding: latin-1 -*-
"""
Graphs Representation
- Matrix (dense) or List (sparse)
Graphs Search algorithms
- Depth First Search
- Breadth First Search
@author: Habib
@contact: Habiboulaye@gmail.com
"""
from Queue import LifoQueue, Queue
# Graphs Representation
class cGraph:
"""
Graphs (Matrix) Representation
"""
def __init__(self, nCount):
self.VertexList=range(nCount)
self.Edges={}
self.Visited={}
self.Dist={}
for i in self.VertexList:
for j in self.VertexList:
self.Edges[(i,j)]=False
self.initVisit()
def initVisit(self):
for i in self.VertexList:
self.Visited[i]=False
def addEdge(self,i,j,dist=None):
self.Edges[(i,j)]=True
self.Edges[(j,i)]=True
if dist:
self.Dist[(i,j)]=dist
self.Dist[(j,i)]=dist
def setVisited(self,i):
self.Visited[i]=True
def printGraph(self):
print (self.VertexList)
print (self.Edges)
print (self.Visited)
# Graphs Search algorithms
def recursiveDFS(Graph, vroot):
"""
Depth First Search: recursive version
"""
iV=vroot
print ("Visit :", iV)
Graph.setVisited(iV)
for jV in Graph.VertexList:
if Graph.Edges[iV,jV] and not Graph.Visited[jV]:
recursiveDFS(Graph, jV)
def stackDFS(Graph, vroot):
"""
Depth First Search: stack version
"""
Stack=LifoQueue()
Stack.put(vroot)
while not Stack.empty():
iV=Stack.get()
print ("Visit :", iV)
Graph.setVisited(iV)
for jV in Graph.VertexList:
if Graph.Edges[iV,jV] and not Graph.Visited[jV]:
Stack.put(jV)
def BFS(Graph, vroot):
"""
Breadth First Search
"""
FIFO=Queue()
FIFO.put(vroot)
while not FIFO.empty():
iV=FIFO.get()
print ("Visit :", iV)
Graph.setVisited(iV)
for jV in Graph.VertexList:
if Graph.Edges[iV,jV] and not Graph.Visited[jV]:
FIFO.put(jV)