二分图

二分图算法也称为染色法,是一种广度优先搜索。如果可以用两种颜色对图中的节点进行着色,并且保证相邻的节点颜色不同,那么图为二分。

Is Graph Bipartite?

题目:

You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. 判断无向图是否是二分图。

题解:

用队列和广度优先搜索,我们可以对未染色的节点进行染色,并且检查是否有颜色相同的相邻节点存在。注意在代码中,我们用 0 表示未检查的节点,用 1 和 2 表示两种不同的颜色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
if (n == 0)
return true;
vector<int> color(n, 0);
queue<int> q;
for (int i = 0; i < n; ++i) {
if (!color[i]) {
q.push(i);
color[i] = 1;
}
while (!q.empty()) {
int node = q.front();
q.pop();
for (const int & j: graph[node]) {
if (color[j] == 0) {
q.push(j);
color[j] = (color[node] == 2) ? 1 : 2;
}
else if (color[node] == color[j])
return false;
}
}
}
return true;
}

拓扑排序

拓扑排序(topological sort)是一种常见的,对有向无环图排序的算法。给定有向无环图中的 N 个节点,我们把它们排序成一个线性序列;若原图中节点 i 指向节点 j,则排序结果中 i 一定在 j 之前。拓扑排序的结果不是唯一的。

Course Schedule II

题目:

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

题解:

我们可以先建立一个邻接矩阵表示图,方便进行直接查找。这里注意我们将所有的边反向,使得如果课程 i 指向课程 j,那么课程 i 需要在课程 j 前面先修完。这样更符合我们的直观理解。

拓扑排序也可以被看成是广度优先搜索的一种情况:我们先遍历一遍所有节点,把入度为 0 的节点(即没有前置课程要求)放在队列中。在每次从队列中获得节点时,我们将该节点放在目前排序的末尾,并且把它指向的课程的入度各减 1;如果在这个过程中有课程的所有前置必修课都已修完(即入度为 0),我们把这个节点加入队列中。当队列的节点都被处理完时,说明所有的节点都已排好序,或因图中存在循环而无法上完所有课程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> indegree(numCourses, 0), res;
for (const auto & prerequisite: prerequisites) {
graph[prerequisite[1]].push_back(prerequisite[0]);
++indegree[prerequisite[0]];
}
queue<int> q;
for (int i = 0; i < indegree.size(); ++i) {
if (!indegree[i])
q.push(i);
}
while (!q.empty()) {
int u = q.front();
res.push_back(u);
q.pop();
for (auto v: graph[u]) {
--indegree[v];
if (!indegree[v])
q.push(v);
}
}
for (int i = 0; i < indegree.size(); ++i) {
if (indegree[i])
return vector<int>();
}
return res;
}

练习

All Paths from Source Lead to Destination

尊贵的 vip 题🤣

题目:

Given the edges of a directed graph, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually end at destination, that is:

  • At least one path exists from the source node to the destination node
  • If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination.
  • The number of possible paths from source to destination is a finite number.

Return true if and only if all roads from source lead to destination.

题解:

回溯,注意判断回路。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
vector<bool> visited(n, false);
vector<vector<int>> m(n);
for(auto& e : edges)
m[e[0]].push_back(e[1]);
if(!m[destination].empty())
return false; //终点后面还有路径
return dfs(m,visited,source,destination);
}
bool dfs(vector<vector<int>>& m, vector<bool>& visited, int cur, int destination) {
if(m[cur].size() == 0 && cur != destination)
return false; //到达一个终点,但不是目标点
for(int next : m[cur]) {
if(visited[next])
return false; //有环
visited[next] = true;
if(!dfs(m, visited, next, destination))
return false;
visited[next] = false; //回溯
}
return true;
}

Connecting Cities With Minimum Cost

题目:

There are N cities numbered from 1 to N.

You are given connections, where each connections[i] = [city1, city2, cost] represents the cost to connect city1 and city2 together. (A connection is bidirectional: connecting city1 and city2 is the same as connecting city2 and city1.)

Return the minimum cost so that for every pair of cities, there exists a path of connections (possibly of length 1) that connects those two cities together. The cost is the sum of the connection costs used. If the task is impossible, return -1.

题解:

法一:

Kruskal's Algorithm:排序后使用并查集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
vector<int> parent;
int find(int i) {
return parent[i] == i? i: parent[i] = find(parent[i]);
}
int minimumCost(int N, vector<vector<int>>& connections) {
parent.resize(N);
iota(parent.begin(), parent.end(), 0);
int costs = 0, count = 1;
sort(connections.begin(), connections.end(), [](auto & conn1, auto & conn2) {return conn1[2] < conn2[2];});
for (auto& conn : connections) {
int ri = find(conn[0]-1), rj = find(conn[1]-1);
if (parent[ri] != rj && parent[rj] != ri) {
costs += conn[2];
parent[ri] = rj;
if (++count == N)
return costs;
}
}
return -1;
}

法二:

Prim's Algorithm: 利用priority queue进行BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int minimumCost(int N, vector<vector<int>>& connections) {
vector<vector<pair<int, int>>> graph(N, vector<pair<int, int>>());
// pair<最短距离,节点编号>
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
unordered_set<int> visited;
int costs = 0;
for (const auto& conn : connections) {
graph[conn[0]-1].push_back(make_pair(conn[2], conn[1]-1));
graph[conn[1]-1].push_back(make_pair(conn[2], conn[0]-1));
}
pq.push(make_pair(0, 0));
while (!pq.empty()) {
auto [cost, city2] = pq.top();
pq.pop();
if (!visited.count(city2)) {
costs += cost;
visited.insert(city2);
for (const auto & v: graph[city2])
pq.push(v);
}
}
return visited.size() == N ? costs : -1;
}

Reachable Nodes In Subdivided Graph

hard ! 😢

题目:

You are given an undirected graph (the “original graph”) with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.

The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.

To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, …, xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], …, [xcnti-1, xcnti], [xcnti, vi].

In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.

Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.

题解:

将原图中的节点称为大节点,新增的称为小节点。

第一步,Dijkstra 算法求出到所有大节点的最短路径长度。

第二步,根据剩余可用长度 maxMoves-steps[x] 求出可到达的小节点数量,为了防止重复计算,按边遍历,用一个哈希表 used 记录各条边上的细分节点的可达情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int encode(int u, int v, int n) {
return u * n + v;
}
int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {
vector<vector<pair<int, int>>> adList(n);
for (auto &edge : edges) {
int u = edge[0], v = edge[1], nodes = edge[2];
adList[u].emplace_back(v, nodes);
adList[v].emplace_back(u, nodes);
}
unordered_map<int, int> used;
unordered_set<int> visited;
int reachableNodes = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.emplace(0, 0);
while (!pq.empty() && pq.top().first <= maxMoves) {
auto [step, u] = pq.top();
pq.pop();
if (visited.count(u))
continue;
visited.emplace(u);
reachableNodes++;
for (auto [v, nodes] : adList[u]) {
if (nodes + step + 1 <= maxMoves && !visited.count(v))
pq.emplace(nodes + step + 1, v);
used[encode(u, v, n)] = min(nodes, maxMoves - step);
}
}
for (auto &edge : edges) {
int u = edge[0], v = edge[1], nodes = edge[2];
reachableNodes += min(nodes, used[encode(u, v, n)] + used[encode(v, u, n)]);
}
return reachableNodes;
}