下面发布的图形代码的DFS遍历是否有任何改进
Can there be any improvements in DFS traversal of graph code posted below?
我想提高这个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[])
您应该看到这些更改的巨大加速。
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 是否可以遍历传递给函数的数组?
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 迭代是否遍历整个列表
- 我是否需要遍历升压 rtree 的层次结构才能实现最大效率?
- 在 std::remove_if 执行期间遍历容器是否安全?
- boost::iterator_adaptor 的遍历类别是否由适配迭代器的类别决定
- 是否可以在 constexpr 函数中遍历枚举成员,因此值为 constexpr
- 是否可以遍历文本文件行并使用字符串流来解析每一行
- 提升 R 树是否支持层次结构遍历
- 是否有一个函数用于遍历POSIX环境变量
- 下面发布的图形代码的DFS遍历是否有任何改进
- 使用迭代器和擦除/添加项遍历QMap是否正确
- 即使边界键不存在,我是否可以遍历 std::map 键范围?
- std::vector 的运算符 [] 是否在<type>每次调用时从头开始遍历向量
- 我们是否可以创建一个类似scanf的函数,当所有参数都填充时返回true,否则返回false,而不循环遍历所有变量?
- 遍历通用STL容器以检查是否存在
- 是否可以遍历一个类以查看一个类或其任何基础是否具有特定的特征?
- 是否可以使用迭代而不是递归来遍历二叉树?