DFS + BFS
深度优先搜索很简单的, 主要是递归, 复杂度一般很高, 是指数级别的
搜索不是一种算法, 而是一种经验, 一种写法, 可以说是暴力
传统搜索结构:
void dfs(int x, ...) {
// 递归终止条件
/* 在当前点对下一个状态进行搜索 {
标记当前点
搜索
取消标记
}
*/
}
广度优先搜索也简单, 主要用到了队列, 采用的是横向搜索
传统结构:
void bfs(int x) {
que.push(x);
vis[x] = 1;
while(que 不为空) {
取出队首;
...;
对下一个状态进行搜索{
标记当前点;
加入队列;
}
}
}
邻接表DFS + BFS
#include <bits/stdc++.h>
using namespace std;
#define MAXN 50000
#define ll long long
struct edge {
int to, cost;
edge(int to, int cost) {
this->to = to;
this->cost = cost;
}
};
vector<edge> e[MAXN];
bool vis[MAXN];
int n, m, x, y, z;
// 起点在 main 中就给 vis[起点] = 1
void dfs(int x, int step) {
cout << x << endl;
for(int i = 0; i < e[x].size(); i++) {
if(!vis[e[x][i].to]) {
vis[e[x][i].to] = 1;
dfs(e[x][i].to, step + 1);
vis[e[x][i].to] = 0;
}
}
}
void bfs(int x) {
queue<int> que;
vis[x] = 1;
que.push(x);
while(!que.empty()) {
int now = que.front();
cout << now << endl;
que.pop();
for(int i = 0; i < e[now].size(); i++) {
if(!vis[e[now][i].to]) {
vis[e[now][i].to] = 1;
que.push(e[now][i].to);
}
}
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= m; i++) {
cin >> x >> y >> z;
e[x].push_back(edge(y, z));
}
bfs(1);
// dfs(1, 0);
return 0;
}
/*
9 10
1 2 1
1 3 1
1 4 1
2 5 1
2 6 1
3 6 1
3 7 1
3 8 1
4 8 1
4 9 1
4 9 1
*/