https://www.bilibili.com/video/BV1q64y1X7jS?from=search&seid=14963115715463379134&spm_id_from=333.337.0.0
邻接表存图模板
#include <isotream>
using namespace std;
int N,M;
struct EDGE{
int u, v, len;
EDGE * nex;
//...
}epool[100001];
struct NODE{ // 出边的链表第一个?
EDGE *fir
//...
}nodes[10001]; // 邻接表!节点存指向边的指针
void addedge(int u, int v, int len){
epool[etop].u=u;
epool[etop].v=v;
epool[etop].len=len;
epool[etop].nex=nodes[u].fir;
nodes[u].fir=&epool[etop];
etop++
}
int main(){
int i,u,v,len;
cin>>N>>M;
for(i=1;i<=M;i++){
cin>>u>>v>>len;
addedge(u,v,len); // 加一条单向边
}
// 这样遍历 id 号点的出边
/*
EDGE *e = nodes[id].fir;
while(e!=NULL){
//e->v ...
//e->u ...
e = e->nex;
*/
system("pause");
return 0;
}
一般搜索算法的流程框架
- 定义点集 X X X 为已经处理过的点,点集 F F F 为一发现但尚未处理的点
- 初始化点集 X X X 为空,点集 F F F 只包含搜索的起点
- 只要点集
F
F
F 不为空,循环
3.1~3.3
3.1 从点集 F F F 中取出一个点
3.2 处理点 v v v,把点 v v v 加入点集 X X X
3.3 遍历 v v v 的出边,对于每个 v v v 的邻居,若即不再点集 X X X 中、也不再点集 F F F 中,则加入点集 F F F - 搜索结束,点集 X X X 里的点是搜索过的点
- 栈 F 2) 递归 —— DFS
队列 F —— BFS
优先队列?
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
// 建图
int N,M,etop;
struct EDGE{
int u,v;
EDGE *nex;
}epool[100001];
struct NODE{
EDGE *fir;
}nodes[10001];
void addedge(int u, int v){
epool[etop].u = u;
epool[etop].v = v;
epool[etop].nex = nodes[i].fir;
nodes[u].fir = &epool[etop];
etop++;
}
// ===== 递归DFS =====
bool visited[10001];
void DFS(int id){
visited[id]=treu;
cout<<id<<' ';
EDGE *e = nodes[id].fir;
while(e!=NULL){
if(!visited[e->v]) DFS(e->v);
e = e->nex;
}
}
// ===== 一般搜索 =====
bool discovered[10001];
stack<int> F;
//queue<int> F;
void search(){
F.push(1);
discovered[1] = true;
while(!F.empty()){
int id = F.top();
//int id = F.front();
F.top();
cout << id << ' ';
EDGE *e = nodes[id].fir;
while(e!=NULL){
if(!discovered[e->v]){
F.push(e->v);
discovered[e->v]=true;
}
e = e->nex;
}
}
}
int main(){
int i,u,v;
cin >> N >> M;
for(i = 1; i <= M; i++){
cin >> u >> v;
addedge(u,v);
addedge(v,u);
}
DFS(1);
cout << endl;
search();
cout << endl;
system("pause");
return 0;
}