Completed
Push — master ( 72947f...dc545e )
by Xianshun
01:51
created

BreadthFirstSearch.__init__()   A

Complexity

Conditions 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 16
rs 9.2
1
from abc import ABCMeta, abstractmethod
2
3
from pyalgs.data_structures.commons.queue import Queue
4
from pyalgs.data_structures.commons.stack import Stack
5
6
7
class Paths(object):
8
    __metaclass__ = ABCMeta
9
10
    @abstractmethod
11
    def pathTo(self, v):
12
        pass
13
14
    @abstractmethod
15
    def hasPathTo(self, v):
16
        pass
17
18
19
class DepthFirstSearch(Paths):
20
    marked = None
21
    edgesTo = None
22
    s = None
23
24
    def __init__(self, G, s):
25
        self.s = s
26
        vertex_count = G.vertex_count()
27
        self.marked = [False] * vertex_count
28
        self.edgesTo = [-1] * vertex_count
29
        self.dfs(G, s)
30
31
    def dfs(self, G, v):
32
        self.marked[v] = True
33
        for w in G.adj(v):
34
            if not self.marked[w]:
35
                self.edgesTo[w] = v
36
                self.dfs(G, w)
37
38
    def hasPathTo(self, v):
39
        return self.marked[v]
40
41
    def pathTo(self, v):
42
        x = v
43
        path = Stack.create()
44
        while x != self.s:
45
            path.push(x)
46
            x = self.edgesTo[x]
47
        path.push(self.s)
48
        return path.iterate()
49
50
51
class BreadthFirstSearch(Paths):
52
53
    marked = None
54
    s = None
55
    edgeTo = None
56
57
    def __init__(self, G, s):
58
        self.s = s
59
        vertex_count = G.vertex_count()
60
        self.marked = [False] * vertex_count
61
        self.edgeTo = [-1] * vertex_count
62
63
        queue = Queue.create()
64
65
        queue.enqueue(s)
66
        while not queue.is_empty():
67
            v = queue.dequeue()
68
            self.marked[v] = True
69
            for w in G.adj(v):
70
                if not self.marked[w]:
71
                    self.edgeTo[w] = v
72
                    queue.enqueue(w)
73
74
    def hasPathTo(self, v):
75
        return self.marked[v]
76
77
    def pathTo(self, v):
78
        x = v
79
        path = Stack.create()
80
        while x != self.s:
81
            path.push(x)
82
            x = self.edgeTo[x]
83
        path.push(self.s)
84
        return path.iterate()