L2-031 深入虎穴——最短路模型

这篇文章展示了如何使用C++编程实现DFS(深度优先搜索)和BFS(广度优先搜索)算法,以在给定的图中找出最大深度的节点及其编号。在DFS中,通过递归函数更新最大深度和对应的节点ID。而在BFS中,利用队列进行迭代,同样找到最大深度。此外,还提供了求解路径的方法。
摘要由CSDN通过智能技术生成

DFS

#include<bits/stdc++.h>

using namespace std;
int n,res,id;//res最大深度,id最大深度的编号
const int N = 1e5 + 10;
vector<int> v[N];
bool st[N];

int dfs(int u,int sum)
{
	if (sum > res)
		res = sum,id = u;
	
	for (auto x : v[u])
		dfs(x, sum + 1);

}

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i]) 
			start = i;
	dfs(start,1);
	cout << id;
}

BFS

#include<bits/stdc++.h>
using namespace std;
int n, res, id;
const int N = 1e5 + 10;
vector<int> v[N];
bool st[N];

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i])
			start = i;

	queue<int> q;
	q.push(start);
	while (q.size())
	{
		int t = q.front();
		q.pop();
		if (q.size() == 0)  res = t;
		for (auto x : v[t])
			q.push(x);
	}
	cout << res;

}

如果还想求一下路径的话

#include<bits/stdc++.h>
using namespace std;
int n, res, id;
const int N = 1e5 + 10;
vector<int> v[N];
bool st[N];
int pre[N];

int main()
{
	cin >> n;
	for (int i = 1;i <= n;i++)
	{
		int cnt;cin >> cnt;
		while (cnt--)
		{
			int t;cin >> t;
			st[t] = true;
			v[i].push_back(t);
		}
	}
	int start;
	for (int i = 1;i <= n;i++)
		if (!st[i])
			start = i;

	queue<int> q;
	q.push(start);
	pre[start] = -1;
	while (q.size())
	{
		int t = q.front();
		q.pop();
		if (q.size() == 0)  res = t;
		for (auto x : v[t])
		{
			q.push(x);
			pre[x] = t;
		}
	}
	cout << res << endl;
	vector<int> path;
	while (pre[res] != -1)
	{
		path.push_back(res);
		res = pre[res];
	}path.push_back(start);
	reverse(path.begin(), path.end());
	for (auto x : path) cout << x << " ";
}

 很明显bfs来做,这里用dist既表示了距离也有st数组的功能

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int dist[N];
int n, k;
int bfs(int x)
{
	queue<int> q;
	q.push(x);
	memset(dist, -1, sizeof dist);
	dist[x] = 0;


	while (q.size())
	{
		int t = q.front();
		q.pop();

		if (t - 1 >= 0 && t - 1 < N&& dist[t-1]==-1)
	        q.push(t - 1), dist[t - 1] = dist[t] + 1;
	
		if (t + 1 >= 0 && t + 1 < N && dist[t+1]==-1)
		    q.push(t + 1), dist[t + 1] = dist[t] + 1;
		
		if (2 * t >= 0 && 2 * t < N && dist[2*t]==-1)
		    q.push(2 * t), dist[2 * t] = dist[t] + 1;

		if (dist[k] != -1) return dist[k];
	}
	return -1;
}

int main()
{

	cin >> n >> k;
	cout << bfs(n);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值