图深度优先算法(DFS)
Posted 工科狗和生物喵
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图深度优先算法(DFS)相关的知识,希望对你有一定的参考价值。
正文之前
好久没弄C++了,上学期颓废了半学期,这学期开学就搞课程设计快疯了。待会要考试CSP,所以弄点代码储备,待会到了考场说不定能省点功夫!
正文
#include <iostream>
#include<vector>
#define Max 1000;
using namespace std;
struct Graph
{
int a[10][10];
};
vector<int> path;
bool visited[10];
int deepth=0;
void DFS(Graph tu,int start)
{
visited[start]=true;
for(int i=0;i<10;i++)
{
if (visited[i]==false && (tu.a)[start][i]<1000)
{
visited[i]=true;
path[deepth]=i;
++deepth;
DFS(tu,i);
}
}
}
// 1 4 1 3 1 5 2 5 2 3 4 5 5 6 5 7
int main()
{
Graph tu;
for(auto &s:tu.a)
for(auto &x:s)
x=Max;
int a,b,s;
path.push_back(0);
for(auto &x:visited)
x=false;
for(int i=0;i<8;++i)
{
cin>>a>>b;
tu.a[a][b]=tu.a[b][a]=1;
path.push_back(0);
}
path[deepth]=1;
++deepth;
DFS(tu,1);
cout<<"====~ The Path is ~====="<<endl;
for(auto &s:path)
if(s!=0)
cout<<"\""<<s<<"\""<<" --> ";
cout<<" | Stop ~ "<<endl;
}
Output:
Last login: Sun Mar 18 11:44:22 on ttys000
= * = * = * = * = * = * = * = * = * = * = * = * = * = *
✧。٩(ˊᗜˋ)و✧* Hello! Welcome 张照博!!开启愉快的一天吧!
= * = * = * = * = * = * = * = * = * = * = * = * = * = *
HustWolf:~ zhangzhaobo$ /Users/zhangzhaobo/program/C++/DFS ; exit;
1 4 1 3 1 5 2 5 2 3 4 5 5 6 5 7
====~ The Path is ~=====
"1" --> "3" --> "2" --> "5" --> "4" --> "6" --> "7" --> | Stop ~
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[进程已完成]
正文之后
祝我好运!发誓这次考试后一定苦学!上学期太飘了。
以上是关于图深度优先算法(DFS)的主要内容,如果未能解决你的问题,请参考以下文章