Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
test_util.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// Unit test utilities related to graph.h.
15
16#ifndef UTIL_GRAPH_TEST_UTIL_H_
17#define UTIL_GRAPH_TEST_UTIL_H_
18
19#include <cstdint>
20#include <memory>
21
22#include "absl/memory/memory.h"
23#include "ortools/base/types.h"
24#include "ortools/graph/graph.h"
25
26namespace util {
27
28// Generate a 2-dimensional undirected grid graph.
29//
30// Eg. for width=3, height=2, it generates this:
31// 0 <---> 1 <---> 2
32// ^ ^ ^
33// | | |
34// v v v
35// 3 <---> 4 <---> 5
36template <class Graph>
37std::unique_ptr<Graph> Create2DGridGraph(int64_t width, int64_t height) {
38 const int64_t num_arcs = 2L * ((width - 1) * height + width * (height - 1));
39 auto graph = std::make_unique<Graph>(/*num_nodes=*/width * height,
40 /*arc_capacity=*/num_arcs);
41 // Add horizontal edges.
42 for (int i = 0; i < height; ++i) {
43 for (int j = 1; j < width; ++j) {
44 const int left = i * width + (j - 1);
45 const int right = i * width + j;
46 graph->AddArc(left, right);
47 graph->AddArc(right, left);
48 }
49 }
50 // Add vertical edges.
51 for (int i = 1; i < height; ++i) {
52 for (int j = 0; j < width; ++j) {
53 const int up = (i - 1) * width + j;
54 const int down = i * width + j;
55 graph->AddArc(up, down);
56 graph->AddArc(down, up);
57 }
58 }
59 graph->Build();
60 return graph;
61}
62
63} // namespace util
64
65#endif // UTIL_GRAPH_TEST_UTIL_H_
A collections of i/o utilities for the Graph classes in ./graph.h.
std::unique_ptr< Graph > Create2DGridGraph(int64_t width, int64_t height)
Definition test_util.h:37