dfs算法求路径,其实就是递归搜索,如果到了已经走过的点且没到终点,就对栈进行操作,排出不需要的节点,不需要的节点,就是这个节点的所有邻节点都走过了,那这个节点肯定不是简单路径里面的一个节点,那么就需要pop出来,
至于求最短路,实验没说一定要用搜索,那么我用dijkstra应该也行吧,dijkstra的话其实就是经过一个节点的时候,就用这个节点到邻节点的距离对原点到这个邻节点的距离进行更新,我记得是叫松弛操作好像,然后一直松弛,就能得到存有原点到每个点的最短距离,其实也不是很难。
我的实验偏向于意识流,代码长只可意会不可言传,本人又菜写的bug又多,发出来仅供参考,能自己写最好。
#include <iostream>
#include<bits/stdc++.h>
#define N 100010
using namespace std;
typedef pair<int,int>p;
vector<p>h[N];
int dist[N];
int st[N];
int m[100][100];
void dijkstra()
{
memset(dist,0x3f3f3f,sizeof(dist));
priority_queue<p,vector<p>,greater<p>>q;
dist[1]=0;
q.push({0,1});
while(!q.empty())
{
p now=q.top();
q.pop();
int ne=now.second;
if(st[ne])continue;
st[ne]=1;
for(auto it:h[ne])
{
dist[it.first]=min(dist[it.first],dist[ne]+it.second);
q.push({dist[it.first],it.first});
}
}
}
int lu[N];//记录已经走过的点
bool pan=false;//判断是否已经走到我们要到的点
stack<int>s;//栈 用来存路径
int x,y;
void dfs(int x,int y)
{
if(pan)
return;
if(lu[x]==1)//如果已经到了走过的地方且没到我们要到的点就进行判断,把不需要的点pop
{
int p=1;
while(p){
int q=s.top();
int z=0;
for(auto t:h[q])
{
if(!lu[t.first])
{
z=1;
break;
}
}
if(z==0)
{
s.pop();
}
else
{
p=0;
}
}
return;
}
lu[x]=1;
s.push(x);
for(auto it:h[x])
{
if(it.first==y&&!lu[y])//如果到了终点就标记走过然后将判断到终点的标记改为true表示已经到了
{
s.push(y);
lu[y]=1;
pan=true;
}
else
dfs(it.first,y);
}
}
int main()
{
memset(m,0x3f,sizeof(m));
int n;
cout<<"输入要输入的路径数量:";
cin>>n;
cout<<"输入所有路径的两个端点和路径长度:"<<endl;
for(int i=1;i<=n;i++)
{
int u,v,w;
cin>>u>>v>>w;
m[u][v]=w;
m[v][u]=m[u][v];
h[u].push_back({v,w});
h[v].push_back({u,w});
}
cout<<"输入要查找路径的两个点:";
cin>>x>>y;
cout<<"输出这两点之间的路径:";
memset(lu,0,sizeof(lu));
dfs(x,y);
int co[100];
int o=0;
while(!s.empty())
{
o++;
co[o]=s.top();
s.pop();
}
for(int i=o;i>=1;i--)cout<<co[i]<<" ";
cout<<endl;
cout<<"输入要查找的点:";
cin>>y;
dijkstra();//没说找最短路一定要用搜索,我用dijkstra应该也没有问题吧,大概
cout<<"输出原点到这个点的最短路:";
cout<<dist[y]<<endl;
return 0;
}