DFS例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bleedingfight/article/details/82530407

问题来自美团笔试

输入一行表示节点数,接下来输入边,求从根节点访问所有节点的最短路径。

         1
      /      \
    2        3
             /  \
           4     5
                    \
                     6

最短路径为:1-2-1-3-4-3-5-6.

思路

每个节点访问的时候只有最大深度的路径访问一次,其他都访问两次,访问路径最短为: × 2

这里DFS第二个参数用来保存当前访问的边的数目,最开始,我将代码放在构造函数中,得到的结果都是局部的边数,放在DFS里面又会在递归调用的时候被初始化,放在参数里面正好能作为计数器计数节点,将深度最大值返回给类的全局变量depth

代码

#include <iostream>
#include <vector>
using namespace std;
class Graph{
private:
    int node_nums;
    vector<bool> visited;
    vector<vector<int>> adj;
    int depth;
public:
    Graph(const vector<vector<int>>& j);
    void show();
    void DFS(int start_node,int end_node);
};
Graph::Graph(const vector<vector<int>>& a){
    depth = 0;
    adj = a;
    visited = vector<bool>(adj.size(),true);
}
void Graph::show() {
    cout<<"最大深度为:"<<depth<<"\n";
    cout<<"最小路径为:"<<2*(adj.size()-1)-depth<<"\n";
}
void Graph::DFS(int start_node,int end_node) {
    visited[start_node] = false;
    for(int i=0;i<adj.size();i++){
        if( visited[i] && adj[start_node][i] == 1){
            DFS(i,end_node+1);
        }
    }
    if(end_node>depth)
        depth = end_node;
}
int main() {
//    vector<vector<int>> j = {{0,1,1,0,0,0},
//                            {1,0,0,0,0,0},
//                            {1,0,0,1,1,0},
//                            {0,0,1,0,0,0},
//                            {0,0,1,0,0,1},
//                            {0,0,0,0,1,0}};
    int n;
    while(cin>>n)
    {
        vector<vector<int>> j(n,vector<int>(n,0));
        int a,b;
        for(int i=0;i<n-1;i++)
        {
            cin>>a>>b;
            j[a-1][b-1] = 1;
            j[b-1][a-1] = 1;
        }
        Graph g = Graph(j);
        g.DFS(0,0);
        g.show();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/bleedingfight/article/details/82530407
dfs
今日推荐