当前位置:网站首页>Depth first find all simple paths from vertex u to vertex v in the graph
Depth first find all simple paths from vertex u to vertex v in the graph
2022-07-23 12:50:00 【Pineapple and pineapple treasure】
Preface
I have been reviewing the data structure , For the adjacency matrix, there is an algorithm in the book that outputs a simple path between two vertices , This sounds simple , Think about it , This is not the same as outputting the root node to r Is the node path the same , Maintain a stack , find r The pointer pops the stack empty .
Allied , about U and V Vertices are the same , Maintain a stack , Find... In the figure V The vertices , Directly empty the stack . This is easy for a simple path .
But one of the questions after class is output U To V All simple paths to , When it comes to tracing back my elm head, I have a headache , focused , Also maintain a stack ? But how can we trace back to the last recursive node after bouncing empty ?
Keep thinking , The data structure of gengguohua's teacher gave me a little inspiration , He used a pre Array to record the route , When from a vertex vi Find its adjacent vertex vj When doing an interview , take pre[j] Set as i, So after exiting the search , According to pre Array from vertex v Trace to vertex u, So as to output this message from u To v Simple path of .
Have to say , Teacher gengguohua is a national famous teacher , It's really powerful , But I really can't think of such a clever method .
I learned from teacher gengguohua's Algorithm , According to my own understanding, I wrote a depth that I can understand, and first find the vertex U To the top V All the simple paths to .
Steps are as follows
1 For adjacency matrix
1.1 Create an adjacency matrix
// Find the vertex position function
int LocateVertex(AdjMatrix* G, VertexData v) {
int j, k;
for (k = 0; k < G->vexnum; k++) {
if (G->vertex[k] == v) {
j = k;
break;
}
}
return j;
}
// Establish adjacency matrix representation of directed net graph
void CreateAdjMatrix(AdjMatrix* G) {
int i, j, k, weight;
VertexData v1, v2;
printf(" Enter the number of vertices and edges \n");
scanf("%d,%d", &G->vexnum, &G->arcnum);
// Initialization of side table
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
G->arcs[i][j].adj = ZHENGWUQIONG;// It's just infinite #define ZHENGWUQIONG 65535
}
}
// Vertex table
for (i = 0; i < G->vexnum; i++) {
G->vertex[i]='A' + i;
}
printf(" Input side table \n");
for (k = 0; k < G->arcnum; k++) {
scanf(" %c, %c,%d", &v1, &v2, &weight);
i = LocateVertex(G, v1);
j = LocateVertex(G, v2);
G->arcs[i][j].adj = weight;
// Add the following line to create an undirected graph .
G->arcs[j][i].adj = G->arcs[i][j].adj;
}
}
1.2 initialization path Array and find vertices U And vertex V The subscript
The code is as follows :
LocateVertex function
int LocateVertex(AdjMatrix* G, VertexData v) {
int j, k;
for (k = 0; k < G->vexnum; k++) {
if (G->vertex[k] == v) {
j = k;
break;
}
}
return j;
}
initialization path Array and input vi,vj
int* path = (int*)malloc(sizeof(int) * G.vexnum);
printf(" Enter the two nodes to query , Comma separated \n");
char ci, cj;
scanf(" %c, %c", &ci, &cj);
int vi = LocateVertex(&G, ci);
int vj = LocateVertex(&G, cj);
for (int i = 0; i < MAX; i++) {
visited[i] = 0;
}
FindPath(G, vi, vj, path, -1);
free(path);
1.3 FindPath() function
The next step is to enter FindPath Function .
path Arrays are used to store paths , Think of Yu stack ,d Is the path length , For the initial -1, Equivalent to stack top pointer .
take vi Set as accessed ,d++ after , Put it in the path Array , If vi and vj The same description found v, Then we will path Array output , Every time you output d–, Indicates that you have exited , And will visited Array is set to not accessed , Convenient access to the next node , But because of recursion , If you return to the previous node , that path The array will also look like the previous node , This completes the backtracking , It's perfect .
however visited Arrays are global variables , Therefore, before entering the node every time, the current path The elements in the array are set to have been accessed , This avoids nodes from vi=0 Start searching and search back .
The code is as follows :
void FindPath(AdjMatrix g, int vi, int vj, int* path, int d) {
//d Subscript the element at the top of the stack. The initial subscript is -1;
int i;
++d;
// hold vi Put it in path Array
path[d] = vi;
// Set up vi For visited
visited[vi] = 1;
// If you find vj
if (vi == vj) {
int len = d;
// Bomb empty path Array
for (int j = 0; j <= len; j++) {
printf("%c ", g.vertex[path[j]]);
// Backstack
d--;
// Do not set the root node as not accessed , It's easy to form a dead cycle .
if (j != 0) {
visited[path[j]] = 0;
}
}
printf("\n");
return;
}
for (i = 0; i < g.vexnum; i++) {
// Before entering the node , To put path The elements in the array are set to have been accessed , Avoid the last output path An array of zero visited Circular access caused by array .
for (int len = d; len >= 0; len--) {
visited[path[len]] = 1;
}
if (!visited[i] && g.arcs[vi][i].adj != ZHENGWUQIONG) {
FindPath(g, i, vj, path, d);
}
}
// If you haven't found it after the loop is over, you can withdraw from the stack and set it to be unreachable . It's like walking down a dead end and exiting .
if (i == g.vexnum) {
visited[path[d]] = 0;
d--;
}
}
1.4 test result
The test results are as follows , I found a rather complicated picture .


Find the most complicated A,D
wuhu , It's perfect !
2 For adjacency tables
2.1 Create adjacency list
The side table established by the tail interpolation method here .
// Find the vertex position function
int LocateVertex(AdjList* G, VertexData v) {
int j, k;
for (k = 0; k < G->vexnum; k++) {
if (G->vertexlist[k].data == v) {
j = k;
break;
}
}
return j;
}
// Create adjacency table
void CreateAdjList(AdjList* adjlist) {
int i, j, k, weight;
char vi, vj;
printf(" Please enter the number of vertices and edges :\n");
scanf("%d,%d", &adjlist->vexnum, &adjlist->arcnum);
for (i = 0; i < adjlist->vexnum; i++) {
adjlist->vertexlist[i].data = 'A' + i;
adjlist->vertexlist[i].firstarc = NULL;
}
printf(" Please enter the starting point of the arc , End point and weight :\n");
for (k = 0; k < adjlist->arcnum; k++) {
scanf(" %c ,%c,%d", &vi, &vj, &weight);
ArcNode* p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = LocateVertex(adjlist, vj);
ArcNode* tmp = adjlist->vertexlist[LocateVertex(adjlist, vi)].firstarc;
if (tmp == NULL) {
p->nextarc = adjlist->vertexlist[LocateVertex(adjlist, vi)].firstarc;
adjlist->vertexlist[LocateVertex(adjlist, vi)].firstarc = p;
}
else {
while (tmp->nextarc != NULL) {
tmp = tmp->nextarc;
}
p->nextarc = tmp->nextarc;
tmp->nextarc = p;
}
// An undirected graph has
ArcNode* s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = LocateVertex(adjlist, vi);
ArcNode* tmp2 = adjlist->vertexlist[LocateVertex(adjlist, vj)].firstarc;
if (tmp2 == NULL) {
s->nextarc = adjlist->vertexlist[LocateVertex(adjlist, vj)].firstarc;
adjlist->vertexlist[LocateVertex(adjlist, vj)].firstarc = s;
}
else {
while (tmp2->nextarc != NULL) {
tmp2 = tmp2->nextarc;
}
s->nextarc = tmp2->nextarc;
tmp2->nextarc = s;
}
}
}
2.2 initialization path Array and find vertices U And vertex V The subscript
Almost and 1.2 As like as two peas
int* path = (int*)malloc(sizeof(int) * G.vexnum);
printf(" Enter the two nodes to query , Comma separated \n");
char ci, cj;
scanf(" %c, %c", &ci, &cj);
int vi = LocateVertex(&G, ci);
int vj = LocateVertex(&G, cj);
for (int i = 0; i < MAX; i++) {
visited[i] = 0;
}
FindPath(G, vi, vj, path, -1);
free(path);
2.3 FindPath() function
And the method of adjacency matrix is also similar
// Depth first find the vertex u And vertex v Simple path of
void FindPath(AdjList g, int vi, int vj, int* path, int d) {
visited[vi] = 1;
d++;
path[d] = vi;
if (vi == vj) {
int i;
for (i = 0; i <= d; i++) {
printf("%c ", g.vertexlist[path[i]].data);
if (i != 0) {
visited[path[i]] = 0;
}
}
printf("\n");
return;
}
ArcNode* p = g.vertexlist[vi].firstarc;
while (p != NULL) {
for (int len = d; len >= 0; len--) {
visited[path[len]] = 1;
}
if (!visited[p->adjvex]) {
FindPath(g, p->adjvex, vj, path, d);
}
p = p->nextarc;
}
if (p == NULL) {
visited[path[d]] = 0;
d--;
}
}
2.4 test result
Or this picture 

There must be no problem .
perfect!
summary
Although this algorithm is a little stupid , But my elm head can understand , I feel very successful !
边栏推荐
- 浅做一下思科实验吧!
- Unity3d: ugui source code, rebuild optimization
- 如何解决if语句太多
- 浅析互联网协议(一)
- Explain the interactive data flow and block data flow of TCP in detail
- Unity3D+moba+技能指示器(一)
- Knowledge points and skills of Wireshark network analysis is so simple
- GameFramework:打包资源,打随app发布包,打包生成文件夹说明,上传资源至服务器,下载资源,GameFreamworkList.dat 与GameFrameworkVersion.dat
- Explain the release of TCP connection in detail
- 在二叉排序树中删除节点
猜你喜欢

Unity3D高清渲染管线无法在模型上播放视频

HCIP---OSPF细节讲解

InheritableThreadLocal与阿里的TransmittableThreadLocal设计思路解析

学习日记——(路由与交换技术)网络地址转换 NAT技术

C#(CSharp) 微信公众号开发一 基本配置

Unity在URP管线下使用TriLib插件加载模型材质不正确的问题

GameFramework:资源热更代码分析,检查版本信息,下载版本文件,校验版本文件,得到更新文件数量,下载文件,TaskPool
![[AUTOSAR storage stack NVM]](/img/7a/15e01f8ace647b55e11e764dba1b64.png)
[AUTOSAR storage stack NVM]

【读书笔记《凤凰架构》- 构架可靠的大型分布式系统.周志明】(一)

Unity3d:UGUI,UI与特效粒子层级,2018.2以上版本BakeMesh,粒子在两个Image之间且在ScrollView
随机推荐
0动态规划 LeetCodde313. 超级丑数
unity3d:UGUI源码EventSystem输入系统常见问题
HCIP---BGP相关配置(联邦篇)
hot 100 动态规划
Three versions and optimization of quick sorting by interval -- friends may not know it
@Requiredargsconstructor annotation use
Briefly describe the similarities and differences between raft and Paxos in design
剖析Redis服务器
剖析Redis中的Sentinel模式
Analyze redis server
详解各种网络协议
【读书笔记《凤凰架构》- 构架可靠的大型分布式系统.周志明】(一)
Unity3d: ugui source code, rebuild optimization
C # custom stack
超好用的抓包工具tcpdump
ThreadLocal到底在干嘛?
Explain the flow control mechanism and congestion control mechanism of TCP in detail
HCIP---GRE协议和MGRE环境,以及OSPF协议的相关知识点
Unity3d:特效对象池,超时删除池内GameObject,GC权值
[AUTOSAR DCM 1. module introduction (DSL, DSD, DSP)]