Google OR-Tools v9.9
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-2024 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 OR_TOOLS_GRAPH_EULERIAN_PATH_H_
30#define OR_TOOLS_GRAPH_EULERIAN_PATH_H_
31
32#include <vector>
33
35
36namespace operations_research {
37
38namespace internal {
39template <typename Graph>
40bool GraphIsConnected(const Graph& graph);
41} // namespace internal
42
43// Returns true if a graph is Eulerian, aka all its nodes are of even degree.
44template <typename Graph>
45bool IsEulerianGraph(const Graph& graph, bool assume_connectivity = true) {
46 typedef typename Graph::NodeIndex NodeIndex;
47 for (const NodeIndex node : graph.AllNodes()) {
48 if ((graph.OutDegree(node) + graph.InDegree(node)) % 2 != 0) {
49 return false;
50 }
51 }
52 return assume_connectivity || internal::GraphIsConnected(graph);
53}
54
55// Returns true if a graph is Semi-Eulerian, aka at most two of its nodes are of
56// odd degree.
57// odd_nodes is filled with odd nodes of the graph.
58template <typename NodeIndex, typename Graph>
59bool IsSemiEulerianGraph(const Graph& graph, std::vector<NodeIndex>* odd_nodes,
60 bool assume_connectivity = true) {
61 CHECK(odd_nodes != nullptr);
62 for (const NodeIndex node : graph.AllNodes()) {
63 const int degree = graph.OutDegree(node) + graph.InDegree(node);
64 if (degree % 2 != 0) {
65 odd_nodes->push_back(node);
66 }
67 }
68 if (odd_nodes->size() > 2) return false;
69 return assume_connectivity || internal::GraphIsConnected(graph);
70}
71
72// Builds an Eulerian path/trail on an undirected graph starting from node root.
73// Supposes the graph is connected and is eulerian or semi-eulerian.
74// This is an implementation of Hierholzer's algorithm.
75// If m is the number of edges in the graph and n the number of nodes, time
76// and memory complexity is O(n + m).
77template <typename NodeIndex, typename Graph>
78std::vector<NodeIndex> BuildEulerianPathFromNode(const Graph& graph,
79 NodeIndex root) {
80 typedef typename Graph::ArcIndex ArcIndex;
81 std::vector<bool> unvisited_edges(graph.num_arcs(), true);
82 std::vector<NodeIndex> tour;
83 if (graph.IsNodeValid(root)) {
84 std::vector<NodeIndex> tour_stack = {root};
85 std::vector<ArcIndex> active_arcs(graph.num_nodes());
86 for (const NodeIndex node : graph.AllNodes()) {
87 active_arcs[node] = *(graph.OutgoingOrOppositeIncomingArcs(node)).begin();
88 }
89 while (!tour_stack.empty()) {
90 const NodeIndex node = tour_stack.back();
91 bool has_unvisited_edges = false;
92 for (const ArcIndex arc :
94 node, active_arcs[node])) {
95 const ArcIndex edge = arc < 0 ? graph.OppositeArc(arc) : arc;
96 if (unvisited_edges[edge]) {
97 has_unvisited_edges = true;
98 active_arcs[node] = arc;
99 tour_stack.push_back(graph.Head(arc));
100 unvisited_edges[edge] = false;
101 break;
102 }
103 }
104 if (!has_unvisited_edges) {
105 tour.push_back(node);
106 tour_stack.pop_back();
107 }
108 }
109 }
110 return tour;
111}
112
113// Builds an Eulerian tour/circuit/cycle starting and ending at node root on an
114// undirected graph.
115// This function works only on Reverse graphs
116// (cf. ortools/graph/graph.h).
117// Returns an empty tour if either root is invalid or if a tour cannot be built.
118template <typename NodeIndex, typename Graph>
119std::vector<NodeIndex> BuildEulerianTourFromNode(
120 const Graph& graph, NodeIndex root, bool assume_connectivity = true) {
121 std::vector<NodeIndex> tour;
122 if (IsEulerianGraph(graph, assume_connectivity)) {
123 tour = BuildEulerianPathFromNode(graph, root);
124 }
125 return tour;
126}
127
128// Same as above but without specifying a start/end root node (node 0 is taken
129// as default root).
130template <typename Graph>
131std::vector<typename Graph::NodeIndex> BuildEulerianTour(
132 const Graph& graph, bool assume_connectivity = true) {
133 return BuildEulerianTourFromNode(graph, 0, assume_connectivity);
134}
135
136// Builds an Eulerian path/trail on an undirected graph.
137// This function works only on Reverse graphs
138// (cf. ortools/graph/graph.h).
139// Returns an empty tour if a tour cannot be built.
140template <typename Graph>
141std::vector<typename Graph::NodeIndex> BuildEulerianPath(
142 const Graph& graph, bool assume_connectivity = true) {
143 typedef typename Graph::NodeIndex NodeIndex;
144 std::vector<NodeIndex> path;
145 std::vector<NodeIndex> roots;
146 if (IsSemiEulerianGraph(graph, &roots, assume_connectivity)) {
147 const NodeIndex root = roots.empty() ? 0 : roots.back();
148 path = BuildEulerianPathFromNode(graph, root);
149 }
150 return path;
151}
152
153namespace internal {
154template <typename Graph>
155bool GraphIsConnected(const Graph& graph) {
156 typedef typename Graph::NodeIndex NodeIndex;
157 const NodeIndex n = graph.num_nodes();
158 if (n <= 1) return true;
159 // We use iterative DFS, which is probably the fastest.
161 std::vector<NodeIndex> stack = {0};
162 std::vector<bool> visited(n, false);
163 while (!stack.empty()) {
164 const NodeIndex node = stack.back();
165 stack.pop_back();
166 for (auto arc : graph.OutgoingOrOppositeIncomingArcs(node)) {
167 const NodeIndex neigh = graph.Head(arc);
168 if (!visited[neigh]) {
169 visited[neigh] = true;
170 stack.push_back(neigh);
171 if (++num_visited == n) return true;
172 }
173 }
174 }
175 return false;
176}
177} // namespace internal
178
179} // namespace operations_research
180
181#endif // OR_TOOLS_GRAPH_EULERIAN_PATH_H_
ArcIndexType ArcIndex
Definition graph.h:196
NodeIndexType num_nodes() const
Definition graph.h:211
IntegerRange< NodeIndex > AllNodes() const
BaseGraph implementation -------------------------------------------------—.
Definition graph.h:969
bool IsNodeValid(NodeIndexType node) const
Returns true if the given node is a valid node of the graph.
Definition graph.h:224
NodeIndexType NodeIndex
Definition graph.h:195
ArcIndexType num_arcs() const
Returns the number of valid arcs in the graph.
Definition graph.h:215
BeginEndWrapper< OutgoingOrOppositeIncomingArcIterator > OutgoingOrOppositeIncomingArcsStartingFrom(NodeIndexType node, ArcIndexType from) const
BeginEndWrapper< OutgoingOrOppositeIncomingArcIterator > OutgoingOrOppositeIncomingArcs(NodeIndexType node) const
ArcIndexType OppositeArc(ArcIndexType arc) const
Definition graph.h:1755
NodeIndexType Head(ArcIndexType arc) const
Definition graph.h:1763
ArcIndexType OutDegree(NodeIndexType node) const
ReverseArcStaticGraph<>::OutDegree() and InDegree() work in O(1).
Definition graph.h:1735
ArcIndexType InDegree(NodeIndexType node) const
Definition graph.h:1741
Edge edge
int arc
constexpr bool UsesTwosComplement()
bool GraphIsConnected(const Graph &graph)
In SWIG mode, we don't want anything besides these top-level includes.
bool IsEulerianGraph(const Graph &graph, bool assume_connectivity=true)
Returns true if a graph is Eulerian, aka all its nodes are of even degree.
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)
util::ReverseArcStaticGraph Graph
Type of graph to use.
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)
*vec begin()+0)