当前位置:网站首页>[graph theory brush question-5] Li Kou 1971 Find out if there is a path in the graph
[graph theory brush question-5] Li Kou 1971 Find out if there is a path in the graph
2022-04-23 20:18:00 【smile-yan】
Graph theory brush questions
1971. Find out if there is a path in the graph
Try to catch up with the original question Address
Difficulty and label
Simple difficulty
- Depth-first traversal
- Breadth first traversal
- And find
Title Description
There is one with n Vertex two-way chart , Where each vertex is marked from 0 To n - 1( contain 0 and n - 1). The edges in the graph are represented by a two-dimensional array of integers edges Express , among edges[i] = [ui, vi] It means a vertex ui And vertex vi Two way edges between . Each vertex pair consists of One at most Edge connection , And no vertex has an edge connected to itself .
Please determine whether there is a vertex start Start , To the top end The end of the Effective path .
Here's your array edges And integer n、start and end, If from start To end There is Effective path , Then return to true, Otherwise return to false.
Example 1

Input :n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2
Output :true
explain : Existence by vertex 0 To the top 2 The path of :
- 0 → 1 → 2
- 0 → 2
Example 2

Input :n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5
Output :false
explain : There are no vertices 0 To the top 5 The path of .
- 1 <= n <= 2 * 10^5
- 0 <= edges.length <= 2 * 10^5
- edges[i].length == 2
- 0 <= ui, vi <= n - 1
- ui != vi
- 0 <= start, end <= n - 1
- There are no two-way edges
- There is no edge pointing to the vertex itself
Topic analysis
It's easier to understand , Without adding some fancy scene descriptions . It's similar to the questions I did before, such as 778. Swimming in a rising pool The difference is that the structure of the graph needs to be built by itself , Given are all edges .
So first build the structure of the graph, and then traverse to find the answer .
In order to be more intuitive, I drew the following pictures :
What is given is n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], So when constructing this graph, it can be expressed as multiple groups of vectors , The index of each set of vectors represents the starting point , The elements in the vector are represented as the elements reachable from this starting point , As shown in the figure :

Then start from the starting point X Start , The depth traversal rules are not very different from those before . The specific process can be summarized as :
Looking for a starting point X The corresponding neighbor vector S, Traverse S Each of them Never been interviewed The elements of W, If W == The goal is Y, Then the return true, Otherwise, continue to visit W Neighbors of , Repeat the whole step .
Code implementation
class Solution {
public:
/** * Initialize all paths , According to the matrix given in the title , Into sets of vectors . */
void initPath(const vector<vector<int>>& edges,
vector<vector<int>>& paths) {
for (int i=0; i<edges.size(); i++) {
int source = edges[i][0];
int destination = edges[i][1];
// Undirected graph , Both directions should be recorded
paths[source].push_back(destination);
paths[destination].push_back(source);
}
}
/** * Depth traversal , Until all points are accessed or paths from the starting point are accessed */
bool dfs(vector<vector<int>>& paths,
vector<bool>& visited,
int source,
int destination) {
// The tag has been accessed
visited[source] = true;
// Reach your destination
if (source == destination) {
return true;
}
// Traverse source All reachable neighbors as a starting point
for (int i=0; i<paths[source].size(); i++) {
int newSource = paths[source][i];
// If this point has not been visited , Then continue to look for its neighbors .
if (!visited[newSource] &&
dfs(paths, visited, newSource, destination)) {
return true;
}
}
return false;
}
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>> paths(n);
vector<bool> visited(n, false);
initPath(edges, paths);
return dfs(paths, visited, source, destination);
}
};
The storage structure of the graph should belong to the adjacency table type , Therefore, the time complexity is closely related to the number of edges , If the number of edges is e e e, The number of points is n n n.
- Time complexity : O ( n + e ) O(n+e) O(n+e);
- Spatial complexity : O ( n × e ) O(n\times e) O(n×e), namely p a t h s paths paths Space occupied by variables .
summary
The topic is simple but it is not so easy to do , Need to think more , Look back .
Smileyan
2022.3.30 0:00
版权声明
本文为[smile-yan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210553133130.html
边栏推荐
- Rédaction de thèses 19: différences entre les thèses de conférence et les thèses périodiques
- Unity 模型整体更改材质
- Still using listview? Use animatedlist to make list elements move
- Computing the intersection of two planes in PCL point cloud processing (51)
- Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 127
- Grafana shares links with variable parameters
- MySQL 进阶 锁 -- MySQL锁概述、MySQL锁的分类:全局锁(数据备份)、表级锁(表共享读锁、表独占写锁、元数据锁、意向锁)、行级锁(行锁、间隙锁、临键锁)
- Understanding various team patterns in scrum patterns
- PHP reference manual string (7.2000 words)
- Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)
猜你喜欢
Handwritten Google's first generation distributed computing framework MapReduce

Fundamentals of programming language (2)

LeetCode异或运算

CVPR 2022 | querydet: use cascaded sparse query to accelerate small target detection under high resolution

网络通信基础(局域网、广域网、IP地址、端口号、协议、封装、分用)

. Ren -- the intimate artifact in the field of vertical Recruitment!

AQS learning

selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT

SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions

After route link navigation, the sub page does not display the navigation style problem
随机推荐
Mysql database backup scheme
R语言使用timeROC包计算无竞争风险情况下的生存资料多时间AUC值、使用confint函数计算无竞争风险情况下的生存资料多时间AUC指标的置信区间值
R语言survival包coxph函数构建cox回归模型、ggrisk包ggrisk函数和two_scatter函数可视化Cox回归的风险评分图、解读风险评分图、基于LIRI数据集(基因数据集)
Design of library management database system
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (V)
Solution to PowerDesigner's failure to connect to MySQL in x64 system
本地调用feign接口报404
CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
PIP installation package reports an error. Could not find a version that satisfies the requirement pymysql (from versions: none)
PCL点云处理之计算两平面交线(五十一)
Is the wechat CICC wealth high-end zone safe? How to open an account for securities
Intersection calculation of straight line and plane in PCL point cloud processing (53)
Fundamentals of network communication (LAN, Wan, IP address, port number, protocol, encapsulation and distribution)
ArcGIS js api 4. X submergence analysis and water submergence analysis
R language survival package coxph function to build Cox regression model, ggrisk package ggrisk function and two_ Scatter function visualizes the risk score map of Cox regression, interprets the risk
MySQL 进阶 锁 -- MySQL锁概述、MySQL锁的分类:全局锁(数据备份)、表级锁(表共享读锁、表独占写锁、元数据锁、意向锁)、行级锁(行锁、间隙锁、临键锁)
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
Notes of Tang Shu's grammar class in postgraduate entrance examination English
Local call feign interface message 404
NC basic usage