下面发布的图形代码的DFS遍历是否有任何改进

Can there be any improvements in DFS traversal of graph code posted below?

本文关键字:是否 遍历 任何改 DFS 代码 图形      更新时间:2023-10-16

我想提高这个DFS遍历代码的效率。

我打算为自己创建一个标准代码,以便我可以将其用于在线竞争性编码竞赛,而无需再次编写整个内容,而只需在此代码中进行少量修改。

    #include <iostream>
    #include<vector>
    using namespace std;
    void print_graph(const vector<vector <int> >GRAPH);
    void set_graph( vector<vector <int> >&GRAPH,const unsigned int sz);
    void DFS_Util(const vector<vector <int> >GRAPH,bool visted[]);
    void DFS(const vector<vector <int> >GRAPH,const unsigned int V);
    int main()
    {
    vector<vector <int > >GRAPH;
    int vertices;
    cin>>vertices;
      for(int i=0;i<vertices;i++)
        {   vector<int>temp(vertices,0);
          GRAPH.push_back(temp);
        }
    set_graph(GRAPH,GRAPH.size());
    print_graph(GRAPH);
    DFS(GRAPH,0);
        return 0;
    }
    void print_graph(const vector<vector <int> >GRAPH)
    {   int sz=GRAPH.size();
    for(int i=0;i<sz;i++)
        {
            for(int j=0;j<sz;j++)
        {
          cout<<GRAPH[i][j]<<" ";
        }cout<<endl;
        }
    }
    void set_graph( vector<vector <int> >&GRAPH,const unsigned int sz)
    {
     for(unsigned int i=0;i<sz;i++)
        {
            for(unsigned int j=0;j<sz;j++)
        {
            int c;
            cin>>c;
    GRAPH.at(i).at(j)=c;
        }
        }
    }
    void DFS_Util(const vector<vector <int> >GRAPH,const unsigned int v,bool visted[])
    {
    visted[v]=true;
    cout<<" "<<v;
    for(unsigned int j=0;j<GRAPH.size();j++)
    {
     if(!visted[j]&&GRAPH[v][j]>=1)
       DFS_Util(GRAPH,j,visted);
    }
    }
    void DFS(const vector<vector <int> >GRAPH,const unsigned int V)
    {
        bool *visited=new bool[GRAPH.size()];
        for(unsigned int i=0;i<GRAPH.size();i++)
        {
            visited[i]=false;
        }
        DFS_Util(GRAPH,V,visited);
    }

是的,不要为每个调用复制图形。通过引用传递它,特别是因为你不修改它。

void DFS(const vector<vector <int> > & GRAPH,const unsigned int V)
void DFS_Util(const vector<vector <int> > & GRAPH,const unsigned int v,bool visted[])

您应该看到这些更改的巨大加速。