Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
eulerian_path.h
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// Utility to build Eulerian paths and tours on a graph. For more information,
15// see https://en.wikipedia.org/wiki/Eulerian_path.
16// As of 10/2015, only undirected graphs are supported.
17//
18// Usage:
19// - Building an Eulerian tour on a ReverseArcListGraph:
20// ReverseArcListGraph<int, int> graph;
21// // Fill graph
22// std::vector<int> tour = BuildEulerianTour(graph);
23//
24// - Building an Eulerian path on a ReverseArcListGraph:
25// ReverseArcListGraph<int, int> graph;
26// // Fill graph
27// std::vector<int> tour = BuildEulerianPath(graph);
28//
29#ifndef ORTOOLS_GRAPH_EULERIAN_PATH_H_
30#define ORTOOLS_GRAPH_EULERIAN_PATH_H_
31
32#include <cstdint>
33#include <vector>
34
36
37namespace operations_research {
38
39namespace internal {
40template <typename Graph>
41bool GraphIsConnected(const Graph& graph);
42} // namespace internal
43
44// Returns true if a graph is Eulerian, aka all its nodes are of even degree.
45template <typename Graph>
46bool IsEulerianGraph(const Graph& graph, bool assume_connectivity = true) {
47 typedef typename Graph::NodeIndex NodeIndex;
48 for (const NodeIndex node : graph.AllNodes()) {
49 if ((graph.OutDegree(node) + graph.InDegree(node)) % 2 != 0) {
50 return false;
51 }
52 }
53 return assume_connectivity || internal::GraphIsConnected(graph);
54}
55
56// Returns true if a graph is Semi-Eulerian, aka at most two of its nodes are of
57// odd degree.
58// odd_nodes is filled with odd nodes of the graph.
59template <typename NodeIndex, typename Graph>
60bool IsSemiEulerianGraph(const Graph& graph, std::vector<NodeIndex>* odd_nodes,
61 bool assume_connectivity = true) {
62 CHECK(odd_nodes != nullptr);
63 for (const NodeIndex node : graph.AllNodes()) {
64 const int degree = graph.OutDegree(node) + graph.InDegree(node);
65 if (degree % 2 != 0) {
66 odd_nodes->push_back(node);
67 }
68 }
69 if (odd_nodes->size() > 2) return false;
70 return assume_connectivity || internal::GraphIsConnected(graph);
71}
72
73// Builds an Eulerian path/trail on an undirected graph starting from node root.
74// Supposes the graph is connected and is eulerian or semi-eulerian.
75// This is an implementation of Hierholzer's algorithm.
76// If m is the number of edges in the graph and n the number of nodes, time
77// and memory complexity is O(n + m).
78template <typename NodeIndex, typename Graph>
79std::vector<NodeIndex> BuildEulerianPathFromNode(const Graph& graph,
80 NodeIndex root) {
81 typedef typename Graph::ArcIndex ArcIndex;
82 // Using a vector of uint8_t instead of bool which is much faster here.
83 std::vector<uint8_t> unvisited_edges(graph.num_arcs(), true);
84 std::vector<NodeIndex> tour;
85 if (graph.IsNodeValid(root)) {
86 std::vector<NodeIndex> tour_stack = {root};
87 std::vector<ArcIndex> active_arcs(graph.num_nodes());
88 for (const NodeIndex node : graph.AllNodes()) {
89 active_arcs[node] = *(graph.OutgoingOrOppositeIncomingArcs(node)).begin();
90 }
91 while (!tour_stack.empty()) {
92 const NodeIndex node = tour_stack.back();
93 bool has_unvisited_edges = false;
94 for (const ArcIndex arc :
96 node, active_arcs[node])) {
97 const ArcIndex edge = arc < 0 ? graph.OppositeArc(arc) : arc;
98 if (unvisited_edges[edge]) {
99 has_unvisited_edges = true;
100 active_arcs[node] = arc;
101 tour_stack.push_back(graph.Head(arc));
102 unvisited_edges[edge] = false;
103 break;
104 }
105 }
106 if (!has_unvisited_edges) {
107 tour.push_back(node);
108 tour_stack.pop_back();
109 }
110 }
111 }
112 return tour;
113}
114
115// Builds an Eulerian tour/circuit/cycle starting and ending at node root on an
116// undirected graph.
117// This function works only on Reverse graphs
118// (cf. ortools/graph/graph.h).
119// Returns an empty tour if either root is invalid or if a tour cannot be built.
120template <typename NodeIndex, typename Graph>
121std::vector<NodeIndex> BuildEulerianTourFromNode(
122 const Graph& graph, NodeIndex root, bool assume_connectivity = true) {
123 std::vector<NodeIndex> tour;
124 if (IsEulerianGraph(graph, assume_connectivity)) {
125 tour = BuildEulerianPathFromNode(graph, root);
126 }
127 return tour;
128}
129
130// Same as above but without specifying a start/end root node (node 0 is taken
131// as default root).
132template <typename Graph>
133std::vector<typename Graph::NodeIndex> BuildEulerianTour(
134 const Graph& graph, bool assume_connectivity = true) {
135 return BuildEulerianTourFromNode(graph, 0, assume_connectivity);
136}
137
138// Builds an Eulerian path/trail on an undirected graph.
139// This function works only on Reverse graphs
140// (cf. ortools/graph/graph.h).
141// Returns an empty tour if a tour cannot be built.
142template <typename Graph>
143std::vector<typename Graph::NodeIndex> BuildEulerianPath(
144 const Graph& graph, bool assume_connectivity = true) {
145 typedef typename Graph::NodeIndex NodeIndex;
146 std::vector<NodeIndex> path;
147 std::vector<NodeIndex> roots;
148 if (IsSemiEulerianGraph(graph, &roots, assume_connectivity)) {
149 const NodeIndex root = roots.empty() ? 0 : roots.back();
150 path = BuildEulerianPathFromNode(graph, root);
151 }
152 return path;
153}
154
155namespace internal {
156template <typename Graph>
157bool GraphIsConnected(const Graph& graph) {
158 typedef typename Graph::NodeIndex NodeIndex;
159 const NodeIndex n = graph.num_nodes();
160 if (n <= 1) return true;
161 // We use iterative DFS, which is probably the fastest.
162 NodeIndex num_visited = 1;
163 std::vector<NodeIndex> stack = {0};
164 std::vector<bool> visited(n, false);
165 while (!stack.empty()) {
166 const NodeIndex node = stack.back();
167 stack.pop_back();
168 for (auto arc : graph.OutgoingOrOppositeIncomingArcs(node)) {
169 const NodeIndex neigh = graph.Head(arc);
170 if (!visited[neigh]) {
171 visited[neigh] = true;
172 stack.push_back(neigh);
173 if (++num_visited == n) return true;
174 }
175 }
176 }
177 return false;
178}
179} // namespace internal
180
181} // namespace operations_research
182
183#endif // ORTOOLS_GRAPH_EULERIAN_PATH_H_
NodeIndexType num_nodes() const
Definition graph.h:229
ArcIndexType num_arcs() const
Definition graph.h:233
IntegerRange< NodeIndex > AllNodes() const
Definition graph.h:1146
bool IsNodeValid(NodeIndexType node) const
Definition graph.h:242
BeginEndWrapper< OutgoingOrOppositeIncomingArcIterator > OutgoingOrOppositeIncomingArcsStartingFrom(NodeIndexType node, ArcIndexType from) const
BeginEndWrapper< OutgoingOrOppositeIncomingArcIterator > OutgoingOrOppositeIncomingArcs(NodeIndexType node) const
ArcIndexType OppositeArc(ArcIndexType arc) const
Definition graph.h:1707
NodeIndexType Head(ArcIndexType arc) const
Definition graph.h:1715
ArcIndexType OutDegree(NodeIndexType node) const
Definition graph.h:1686
ArcIndexType InDegree(NodeIndexType node) const
Definition graph.h:1692
bool GraphIsConnected(const Graph &graph)
OR-Tools root namespace.
bool IsEulerianGraph(const Graph &graph, bool assume_connectivity=true)
std::vector< typename Graph::NodeIndex > BuildEulerianPath(const Graph &graph, bool assume_connectivity=true)
std::vector< NodeIndex > BuildEulerianTourFromNode(const Graph &graph, NodeIndex root, bool assume_connectivity=true)
BlossomGraph::NodeIndex NodeIndex
util::ReverseArcStaticGraph Graph
std::vector< typename Graph::NodeIndex > BuildEulerianTour(const Graph &graph, bool assume_connectivity=true)
bool IsSemiEulerianGraph(const Graph &graph, std::vector< NodeIndex > *odd_nodes, bool assume_connectivity=true)
std::vector< NodeIndex > BuildEulerianPathFromNode(const Graph &graph, NodeIndex root)