【知识点:链式前向星】
● 大佬 yxc 指出“链式前向星”就是“多单链表”,并基于“头插法”给出了所涉及到的 e[]、ne[]、h[] 等数组的独特解释,更易理解。其中:
val[idx]:存储编号为 idx 的边的值
e[idx]:存储编号为 idx 的结点的值
ne[idx]:存储编号为 idx 的结点指向的结点的编号
h[a]:存储头结点 a 指向的结点的编号
● 图的“多单链表”示意图如下所示:
注意:图的“多单链表”示意图,读者可与上文提及的 e[]、ne[]、h[] 等数组关联理解。
● 链式前向星的核心代码如下:
(1)加边操作
无权图的链式前向星的加边操作核心代码如下:
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
有权图的链式前向星的加边操作核心代码如下:
void add(int a,int b,int w) {
val[idx]=w,e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
其中,val[] 表示存储权值的数组。
(2)基于链式前向星的深度优先搜索(DFS)的核心代码
void dfs(int u) {
cout<<u<<" ";
st[u]=true;
for(int i=h[u]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
dfs(j);
}
}
}
(3)基于链式前向星的广度优先搜索(BFS)的核心代码
void bfs(int u) {
queue<int>q;
st[u]=true;
q.push(u);
while(!q.empty()) {
int t=q.front();
q.pop();
cout<<t<<" ";
for(int i=h[t]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
q.push(j);
st[j]=true; //need to be flagged immediately after being queued
}
}
}
}
● 无向图及树的深度和广度优先搜索完整代码 ← 链式前向星
来源:https://blog.csdn.net/hnjzsyjyj/article/details/119917795
/* 链式前向星存图
val[idx]:存储编号为 idx 的边的值
e[idx]:存储编号为 idx 的结点的值
ne[idx]:存储编号为 idx 的结点指向的结点的编号
h[a]:存储头结点 a 指向的结点的编号
*/
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
const int M=N<<1;
int n;
int h[N],e[M],ne[M],idx;
bool st[N];
int ans;
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u) {
cout<<u<<" ";
st[u]=true;
for(int i=h[u]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
dfs(j);
}
}
}
void bfs(int u) {
queue<int>q;
st[u]=true;
q.push(u);
while(!q.empty()) {
int t=q.front();
q.pop();
cout<<t<<" ";
for(int i=h[t]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
q.push(j);
st[j]=true; //need to be flagged immediately after being queued
}
}
}
}
int main() {
cin>>n;
memset(h,-1,sizeof(h));
for(int i=0; i<n-1; i++) {
int a,b;
cin>>a>>b;
add(a,b),add(b,a); //undirected graph
}
cout<<"A kind of DFS:"<<endl;
dfs(2); //dfs(i),i is node's name
memset(st,false,sizeof(st));
cout<<endl;
cout<<"A kind of BFS:"<<endl;
bfs(2); //bfs(i),i is node's name
return 0;
}
/*
in:
6
2 1
3 2
4 3
5 2
6 1
out:
A kind of DFS:
2 5 3 4 1 6
A kind of BFS:
2 5 3 1 4 6
*/
【参考文献】
https://www.cnblogs.com/lwtyyds/p/15774070.html
https://blog.csdn.net/hnjzsyjyj/article/details/126474608
https://blog.csdn.net/m0_52620723/article/details/135973510
https://www.acwing.com/file_system/file/content/whole/index/content/4800/yxc125