C++ Reference

C++ Reference: Graph

eulerian_path.h
Go to the documentation of this file.
1 // Copyright 2010-2022 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 
34 #include "ortools/base/logging.h"
35 
36 namespace operations_research {
37 
38 namespace internal {
39 template <typename Graph>
40 bool GraphIsConnected(const Graph& graph);
41 } // namespace internal
42 
43 // Returns true if a graph is Eulerian, aka all its nodes are of even degree.
44 template <typename Graph>
45 bool 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.
58 template <typename NodeIndex, typename Graph>
59 bool 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).
77 template <typename NodeIndex, typename Graph>
78 std::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 :
93  graph.OutgoingOrOppositeIncomingArcsStartingFrom(
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.
118 template <typename NodeIndex, typename Graph>
119 std::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).
130 template <typename Graph>
131 std::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.
140 template <typename Graph>
141 std::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 
153 namespace internal {
154 template <typename Graph>
155 bool 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.
160  NodeIndex num_visited = 1;
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_
bool GraphIsConnected(const Graph &graph)
std::vector< typename Graph::NodeIndex > BuildEulerianPath(const Graph &graph, bool assume_connectivity=true)
bool IsEulerianGraph(const Graph &graph, bool assume_connectivity=true)
Definition: eulerian_path.h:45
std::vector< NodeIndex > BuildEulerianTourFromNode(const Graph &graph, NodeIndex root, bool assume_connectivity=true)
std::vector< typename Graph::NodeIndex > BuildEulerianTour(const Graph &graph, bool assume_connectivity=true)
std::vector< NodeIndex > BuildEulerianPathFromNode(const Graph &graph, NodeIndex root)
Definition: eulerian_path.h:78
bool IsSemiEulerianGraph(const Graph &graph, std::vector< NodeIndex > *odd_nodes, bool assume_connectivity=true)
Definition: eulerian_path.h:59
ListGraph Graph
Definition: graph.h:2398