Passed
Push — master ( 21d80d...504dee )
by Xianshun
01:45
created

Paths   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 10
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A pathTo() 0 3 1
A hasPathTo() 0 3 1
1
from abc import ABCMeta, abstractmethod
2
3
from pyalgs.data_structures.commons.stack import Stack
4
5
6
class Paths(object):
7
    __metaclass__ = ABCMeta
8
9
    @abstractmethod
10
    def pathTo(self, v):
11
        pass
12
13
    @abstractmethod
14
    def hasPathTo(self, v):
15
        pass
16
17
18
class DepthFirstSearch(Paths):
19
    marked = None
20
    edgesTo = None
21
    s = None
22
23
    def __init__(self, G, s):
24
        self.s = s
25
        vertex_count = G.vertex_count()
26
        self.marked = [False] * vertex_count
27
        self.edgesTo = [-1] * vertex_count
28
        self.dfs(G, s)
29
30
    def dfs(self, G, v):
31
        self.marked[v] = True
32
        for w in G.adj(v):
33
            if not self.marked[w]:
34
                self.edgesTo[w] = v
35
                self.dfs(G, w)
36
37
    def hasPathTo(self, v):
38
        return self.marked[v]
39
40
    def pathTo(self, v):
41
        x = v
42
        path = Stack.create()
43
        while x != self.s:
44
            path.push(x)
45
            x = self.edgesTo[x]
46
        path.push(self.s)
47
        return path.iterate()
48