Skip to content

Commit 25ce040

Browse files
committed
fix enumerating cycle in undirected graph
1 parent 4cdd703 commit 25ce040

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/sage/graphs/cycle_enumeration.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -164,14 +164,13 @@ def _all_cycles_iterator_vertex(self, vertex, starting_vertices=None, simple=Fal
164164
[0, 1, 0]
165165
[0, 2, 0]
166166
[0, 1, 2, 0]
167-
[0, 2, 1, 0]
168167
[0, 1, 0, 1, 0]
169168
[0, 1, 0, 2, 0]
170169
[0, 1, 2, 1, 0]
170+
[0, 2, 0, 2, 0]
171171
sage: for cycle in g._all_cycles_iterator_vertex(0, simple=True):
172172
....: print(cycle)
173173
[0, 1, 2, 0]
174-
[0, 2, 1, 0]
175174
"""
176175
if starting_vertices is None:
177176
starting_vertices = [vertex]
@@ -195,6 +194,8 @@ def _all_cycles_iterator_vertex(self, vertex, starting_vertices=None, simple=Fal
195194
h.delete_edges((u, v) for u, v in h.edge_iterator(labels=False) if d[u] != d[v])
196195
else:
197196
h = self
197+
int_to_vertex = list(h)
198+
vertex_to_int = {v: i for i, v in enumerate(int_to_vertex)}
198199

199200
by_weight, weight_function = self._get_weight_function(by_weight=by_weight,
200201
weight_function=weight_function,
@@ -212,12 +213,23 @@ def _all_cycles_iterator_vertex(self, vertex, starting_vertices=None, simple=Fal
212213
while heap_queue:
213214
length, path = heappop(heap_queue)
214215
# Checks if a cycle has been found
215-
if len(path) > 1 and path[0] == path[-1] and \
216-
(not simple or self.is_directed() or len(path) > 3):
217-
if report_weight:
218-
yield (length, path)
219-
else:
220-
yield path
216+
if len(path) > 1 and path[0] == path[-1]:
217+
report = True
218+
if not self.is_directed():
219+
if simple and len(path) <= 3:
220+
report = False
221+
L = len(path)
222+
for i in range(1, L // 2):
223+
if path[i] > path[L - i - 1]:
224+
report = False
225+
break
226+
if path[i] < path[L - i - 1]:
227+
break
228+
if report:
229+
if report_weight:
230+
yield (length, path)
231+
else:
232+
yield path
221233
# If simple is set to True, only simple cycles are
222234
# allowed, Then it discards the current path
223235
if (not simple or path.count(path[-1]) == 1):
@@ -575,7 +587,6 @@ def all_cycles_iterator(self, starting_vertices=None, simple=False,
575587
sage: for cycle in g.all_cycles_iterator(algorithm='A', simple=True):
576588
....: print(cycle)
577589
[0, 1, 2, 0]
578-
[0, 2, 1, 0]
579590
"""
580591
if starting_vertices is None:
581592
starting_vertices = self
@@ -876,7 +887,7 @@ def all_simple_cycles(self, starting_vertices=None, rooted=False,
876887
877888
sage: g = Graph({0: [1, 2], 1: [0, 2], 2: [0, 1]})
878889
sage: g.all_simple_cycles(algorithm='A')
879-
[[0, 1, 2, 0], [0, 2, 1, 0]]
890+
[[0, 1, 2, 0]]
880891
"""
881892
return list(self.all_cycles_iterator(starting_vertices=starting_vertices,
882893
simple=True, rooted=rooted,

0 commit comments

Comments
 (0)