思路:
利用栈非递归实现深度优先遍历(DFS)图。先把起始顶点访问并入栈;然后每次取栈顶元素,找到一个与栈顶顶点连接并且未被访问的顶点,随即访问此顶点,并将此顶点入栈;直到某一顶点没有出边(针对有向图)或者所有连接的顶点都已经被访问过了,删除栈顶元素;循环上述步骤,直到栈为空,深度优先遍历结束。
注:深度优先遍历到所有顶点的前提是此图为连通图;若此图为两个连通图组成的图,则需要两次深度优先遍历,每次都取其中一个连通图任一点作为起始顶点。
代码:
#include <iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
typedef int T; //顶点的值类型 int, char, double and so on
struct Node
{
T value; //顶点值
int numbers; //顶点编号
bool operator==(const Node &other)
{
if((this->numbers==other.numbers)&&(this->value==other.value))
return true;
else
return false;
}
Node(int a1=0,int a2=0)
{
numbers=a1;
value=a2;
}
};
struct Edge
{
int num1; //起始顶点
int num2; //终止顶点
int weight; //边所对应的权值
};
class Graph
{
private:
int vertex_nums; //顶点数
int edge_nums; //边数
vector<Node> vertex; //顶点表,强制设为编号从0开始
vector<Edge> edge; //边表
vector<vector<int> > edge_maze; //邻接矩阵,存储各个顶点连接关系
public:
Graph(int n1=10,int n2=10)
{
vertex_nums=n1;
edge_nums=n2;
for(int i=0;i<vertex_nums;i++)
{
Node a;
a.numbers=i;
a.value=0;
vertex.push_back(a);
}
for(int i=0;i<vertex_nums;i++) //邻接矩阵初始化
{
vector<int> temp(vertex_nums,0);
edge_maze.push_back(temp);
}
cout<<"please input the edges about the graph: ver