class
Node:
def
__init__(
self
, val):
self
.val
=
val
self
.
next
=
None
class
queue:
def
__init__(
self
):
self
.head
=
None
self
.tail
=
None
def
empty(
self
):
return
self
.head
=
=
None
def
push(
self
, val):
if
self
.head
is
None
:
self
.head
=
Node(val)
self
.tail
=
self
.head
else
:
self
.tail.
next
=
Node(val)
self
.tail
=
self
.tail.
next
def
pop(
self
):
returned
=
self
.head.val
self
.head
=
self
.head.
next
return
returned
def
bfs(graph, s, t):
N
=
len
(graph)
/
/
2
Q
=
queue()
Q.push(s)
predecessor
=
list
(
-
1
for
_
in
range
(
2
*
N))
predecessor[s]
=
s
while
not
Q.empty():
cur
=
Q.pop()
for
neighbour
in
graph[cur]:
if
neighbour
=
=
t
or
neighbour
=
=
t
+
N:
predecessor[t]
=
cur
predecessor[t
+
N]
=
cur
return
predecessor
if
predecessor[neighbour]
=
=
-
1
:
Q.push(neighbour)
predecessor[neighbour]
=
cur
return
None
def
invert_path(graph, predecessor, flow, s, t):
N
=
len
(graph)
/
/
2
cur
=
t
while
cur !
=
s:
pred
=
predecessor[cur]
if
flow[pred] !
=
cur:
flow[cur]
=
pred
graph[cur].append(pred)
graph[pred].remove(cur)
cur
=
pred
graph[s].append(s
+
N)
return
flow
def
flow_path(flow, first_node, s):
path
=
[]
cur
=
first_node
while
cur !
=
s:
path.append(cur)
cur
=
flow[cur]
return
path
def
cycleWith2Nodes(graph, s
=
0
, t
=
1
):
N
=
len
(graph)
graph
+
=
list
(graph[node]
for
node
in
range
(N))
graph[:N]
=
list
([node
+
N]
for
node
in
range
(N))
predecessor
=
bfs(graph, s, t)
if
predecessor
is
not
None
:
flow
=
list
(
-
1
for
_
in
range
(
2
*
N))
flow
=
invert_path(graph, predecessor, flow, s, t)
first_node
=
flow[t]
else
:
print
(
"No cycle"
)
return
predecessor
=
bfs(graph, s, t)
if
predecessor
is
not
None
:
flow
=
invert_path(graph, predecessor, flow, s, t)
path1
=
flow_path(flow, first_node, s)
path2
=
flow_path(flow, flow[t], s)
path2.reverse()
simpleCycle
=
[s]
+
path2
+
[t]
+
path1
+
[s]
print
(simpleCycle[::
2
])
else
:
print
(
"No cycle"
)
if
__name__
=
=
"__main__"
:
graph
=
[
[
1
,
6
],
[
0
,
2
,
3
],
[
1
,
3
,
5
,
6
],
[
1
,
2
,
4
],
[
3
,
5
],
[
2
,
4
],
[
0
,
2
],
]
cycleWith2Nodes(graph, s
=
0
, t
=
4
)