Skip to content

Commit df69107

Browse files
committed
feat: 重新规划路线
1 parent 381598b commit df69107

5 files changed

+66
-1
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文
547547

548548
###
549549

550+
- [重新规划路线](src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero.cpp) [深度优先搜索, 广度优先搜索, 图]
551+
552+
- LeetCode 1466. 重新规划路线 <https://leetcode.cn/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero>
553+
550554
- [最小化旅行的价格总和](src/graphs/minimize_the_total_price_of_the_trips.cpp) [树, 深度优先搜索, 图, 数组, 动态规划]
551555

552556
- LeetCode 2646. 最小化旅行的价格总和 <https://leetcode.cn/problems/minimize-the-total-price-of-the-trips>
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// 重新规划路线
2+
// https://leetcode.cn/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero
3+
// INLINE
4+
// ../../images/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero.jpeg
5+
6+
#include <headers.hpp>
7+
8+
class Solution {
9+
private:
10+
void dfs(int node, vector<bool> &visited, int &res,
11+
vector<vector<pair<int, bool>>> &graph) {
12+
visited[node] = true;
13+
for (auto &[next, is_out] : graph[node]) {
14+
if (!visited[next]) {
15+
if (is_out) {
16+
res++;
17+
}
18+
dfs(next, visited, res, graph);
19+
}
20+
}
21+
}
22+
23+
public:
24+
int minReorder(int n, vector<vector<int>> &connections) {
25+
int res = 0;
26+
vector<bool> visited(n, false);
27+
vector<vector<pair<int, bool>>> graph(n);
28+
for (auto &connection : connections) {
29+
graph[connection[0]].push_back({connection[1], true});
30+
graph[connection[1]].push_back({connection[0], false});
31+
}
32+
dfs(0, visited, res, graph);
33+
return res;
34+
}
35+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include <graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero.cpp>
2+
3+
TEST(重新规划路线, minReorder) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
7+
// 输出:3
8+
// 解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
9+
int n = 6;
10+
vector<vector<int>> connections = {{0, 1}, {1, 3}, {2, 3}, {4, 0}, {4, 5}};
11+
EXPECT_EQ(solution.minReorder(n, connections), 3);
12+
13+
// 示例 2:
14+
// 输入:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
15+
// 输出:2
16+
// 解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
17+
n = 5;
18+
connections = {{1, 0}, {1, 2}, {3, 2}, {3, 4}};
19+
EXPECT_EQ(solution.minReorder(n, connections), 2);
20+
// 示例 3:
21+
// 输入:n = 3, connections = [[1,0],[2,0]]
22+
// 输出:0
23+
n = 3;
24+
connections = {{1, 0}, {2, 0}};
25+
EXPECT_EQ(solution.minReorder(n, connections), 0);
26+
}

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2023-12-06 09:50:10
1+
// 执行编译时间:2023-12-07 11:57:41
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

0 commit comments

Comments
 (0)