数据结构学习笔记————图 :C++实现输出无向图的连通分量(基于邻接表下的深度优先搜索)

输入格式:

输入第1行给出2个整数N(0

输出格式:

按照"{ v​1​​ v​2​​ ... v​k​​ }"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。

输入样例:

8 6
0 7
0 1
2 0
4 1
2 4
3 5

输出样例:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }

 代码 main.cpp

#include 
#include
using  namespace std;


//边结点类
class edgNode
{
public:
	int index;
	edgNode *next;
	edgNode();
	edgNode(int index_, edgNode * next_ = NULL);


};
inline edgNode::edgNode()
{
	next = NULL;
}
inline edgNode::edgNode(int index_, edgNode * next_)
{
	index = index_;
	next = next_;
}


//顶点结点类
class vexNode
{
public:
	int index;
	edgNode *next;
	vexNode();
	vexNode(int index_, edgNode * next_ = NULL);


};
inline vexNode::vexNode()
{
	next = NULL;
}
inline vexNode::vexNode(int index_, edgNode * next_)
{
	index = index_;
	next = next_;
}



//创建邻接表表示的图
class graph
{
public:
	bool *tag;
	vexNode *vertex;
	int vertex_num;
	int link_num;
	graph(int vertex_num_, int link_num_);//构造函数 指定顶点数目和边的数目 并对相应的顶点数组初始化
	void add_link(int father_index, int son_index);
	void DFS(int v);
	void all_DFS();
	int get_next(int v, int w);
};

inline graph::graph(int vertex_num_, int link_num_)
{
	vertex_num = vertex_num_;
	link_num = link_num_;
	vertex = new vexNode[vertex_num_];
	tag = new bool[vertex_num_];
	for (int i = 0; i < vertex_num; i++)
	{
		vertex[i].index = i;
		tag[i] = 0;
	}
}
inline void graph::add_link(int v1, int v2)
{
	edgNode *p=new edgNode(0, vertex[v1].next);
	vertex[v1].next = new edgNode(v2, p);
	edgNode *q = new edgNode(0, vertex[v2].next);
	vertex[v2].next = new edgNode(v1, q);
}


inline void graph::DFS(int v)
{
	tag[v] = 1;
	cout << v <<" ";
	edgNode *m = vertex[v].next;

	//不应该用数组序号的形式去遍历 因为这样会返回到顶点数组中去 造成死循环
	//int w;
	//for ( w= vertex[v].next->index; w!=-1;  w = get_next(v,w))
	while(m!=NULL)
	{
		if (tag[m->index] == 0)
		{
			DFS(m->index);
		}
		m = m->next;
			
	}
}

inline void graph::all_DFS()
{
	
	
	for (int i = 0; i < vertex_num; i++)
	{
		if (tag[i] == 0)
		{
			cout << "{ ";
			DFS(i);
			cout << " }" << endl;
		}

	}
}

inline int graph::get_next(int v, int w)
{

	edgNode *p;
	p = vertex[v].next;
	while (p != NULL && p->index!= w)
	{
		p = p->next;
	}
	if (p == NULL && p->next == NULL) return -1;
	else
		return p->next->index;

}

int main()
{
	int vertex_num,link_num;
	cin >> vertex_num >> link_num;
	graph test_graph(vertex_num, link_num);

	int link_node1, link_node2;
	cin >> link_node1 >> link_node2;
	
	test_graph.add_link(link_node1, link_node2);

	cin >> link_node1 >> link_node2;
	test_graph.add_link(link_node1, link_node2);

	cin >> link_node1 >> link_node2;
	test_graph.add_link(link_node1, link_node2);

	cin >> link_node1 >> link_node2;
	test_graph.add_link(link_node1, link_node2);

	cin >> link_node1 >> link_node2;
	test_graph.add_link(link_node1, link_node2);

	cin >> link_node1 >> link_node2;
	test_graph.add_link(link_node1, link_node2);

	test_graph.all_DFS();
	system("pause");
	return 0;
}






 

你可能感兴趣的:(数据结构学习笔记————图 :C++实现输出无向图的连通分量(基于邻接表下的深度优先搜索))