图算法-深度优先搜索(DFS)

代码实现

#include <iostream>
#include <vector>
#include <deque>

using namespace std;

class Graph{
public:
    int V;
    Graph(int V):V(V){
        adj = new vector<int>[V];
    };
    ~Graph(){
        delete[] adj;
    };
    void addedge(int src, int dst);
    void printgraph();
    void dfs(int src);
private:
    void backtrace(int src, vector<bool>&visited);
    vector<int> *adj;
};

void Graph::addedge(int src, int dst){
    adj[src].push_back(dst);
    adj[dst].push_back(src);
}


void Graph::printgraph(){
    for(int i = 0; i < V; i++){
        for(auto it:adj[i]){
            cout<<i<<"---->"<<it<<endl;
        }
    }
}

void Graph::backtrace(int src, vector<bool>&visited){
    visited[src] = true;
    cout<<src<<endl;
    //遍历每一个边
    for(auto it:adj[src]){
        if(visited[it] == false){
            backtrace(it, visited);
        }
    }
}
void Graph::dfs(int src){
    vector<bool> visited(V, false);
    backtrace(src, visited);
}

int main(){
    int V,E;
    while(cin>>V>>E){
        Graph mymap(V);
        int src,dst;
        int i = 0;
        while(i < E && cin>>src>>dst){
            if(src < V&& dst < V)
                mymap.addedge(src, dst);
            i++;
        }
        cin>>src;
        cout<<"dfs"<<endl;
        mymap.dfs(src);
    }
    return 0;
}

测试

输入描述:
第一行输出节点个数V和边数E。
接下来输入E行边的源和目的节点。
最后输入深度搜索的起始节点。
输出描述:
输出深度搜索遍历节点的顺序。

admin@ubuntu:~$ g++ dfs.cpp -o dfs --std=c++11
admin@ubuntu:~$ ./dfs                         
4 6 
0 1
0 2
1 2
2 0
2 3
3 3
2

dfs
2
0
1
3
posted @ 2020-01-02 19:11  ouyangxibao  阅读(115)  评论(0)    收藏  举报