c_cpp 图表的DFS
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 图表的DFS相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h>
using namespace std;
// #Graphs #BasicProblem
// https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
// Given graph is a strongly connected directed graph
// (there is atleast 1 path from each vertex to another vertex)
// Testcase
// 1
// 4
// 6
// 0 2
// 0 1
// 1 2
// 2 0
// 2 3
// 3 3
// 2
// Ans: 2 0 1 3
void DFS(vector< vector<int> > AdjL,vector<bool> &visited,int start){
cout<<start<<" ";
visited[start]=true;
for(int i=0;i<AdjL[start].size();i++){
// loop through the current vertex's AdjL and recursively DFS if vertex is not visited
if(visited[AdjL[start][i]]==false){
DFS(AdjL,visited,AdjL[start][i]);
}
}
}
int main(){
freopen("ip.txt","r",stdin);
int t;
cin>>t;
while(t--){
int v;
cin>>v;
vector< vector<int> > AdjL(v);
int e;
cin>>e;
int i=0;
while(i<e){
int a,b;
cin>>a>>b;
AdjL[a].push_back(b);
i++;
}
vector<bool> visited(v,false);
int start;
// cout<<"Enter starting vertex"<<endl;
cin>>start;
cout<<"DFS: ";
DFS(AdjL,visited,start);
cout<<endl;
//======================(Iterative DFS)==========================
// https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1385/
for(int i=0;i<v;i++){
visited[i]=false; // reset visited
}
stack<int> st; // contains id's of vertices
st.push(start);
visited[start]=true;
cout<<"Iterative DFS: "<<endl;
while(!st.empty()){
int currTop=st.top(); // store top in temp var
st.pop(); // and pop the current stack
cout<<currTop<<" ";
for(int i=AdjL[currTop].size()-1;i>=0;i--){ //for left to right
if(!visited[AdjL[currTop][i]]){ // as left element is added last
st.push(AdjL[currTop][i]); // it comes out first
// cout<<currTop<<" ";
visited[AdjL[currTop][i]]=true;
}
}
}
cout<<endl;
}
return 0;
}
以上是关于c_cpp 图表的DFS的主要内容,如果未能解决你的问题,请参考以下文章