邻接表 + DFS + BFS

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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值