-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
80 lines (58 loc) · 1.87 KB
/
graph.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
import fileinput
from more_itertools import take, map_except
class Graph:
__numVertices = 0
__numEdges = 0
__adjacencyLists = []
def __init__(self, numVertices):
self.__numVertices = numVertices
for _ in range(numVertices):
self.__adjacencyLists.append([])
@classmethod
def fromFile(self, file):
f = fileinput.input(file)
header = take(2, f)
numVertices = int(header[0])
numEdges = int(header[1])
graph = Graph(numVertices)
lines = take(numEdges, f)
linesList = list(lines)
linesList.reverse()
for line in linesList:
vw = map_except(int, line, ValueError, TypeError)
vwList = list(vw)
v = vwList[0]
w = vwList[1]
graph.addEdge(v, w)
fileinput.close()
return graph
def get_numVertices(self):
return self.__numVertices
def get_numEdges(self):
return self.__numEdges
numVertices = property(get_numVertices)
numEdges = property(get_numEdges)
def addEdge(self, v, w):
self.__adjacencyLists[v].append(w)
self.__adjacencyLists[w].append(v)
self.__numEdges = self.__numEdges + 1
def adjacencyList(self, v):
return self.__adjacencyLists[v]
class DepthFirstSearch:
__count = 0
__marked = []
def __init__(self, graph, s):
for _ in range(graph.numVertices):
self.__marked.append(False)
self.__dfs(graph, s)
def __dfs(self, graph, v):
self.__marked[v] = True;
self.__count = self.__count + 1
for w in graph.adjacencyList(v):
if (self.__marked[w] != True):
self.__dfs(graph, w)
def isMarked(self, w):
return self.__marked[w]
def get_count(self):
return self.__count
count = property(get_count)