1. 程式人生 > >信管117118李志榮資料結構實驗六---圖的實驗

信管117118李志榮資料結構實驗六---圖的實驗

#include<iostream>
#include<string>
using namespace std;
template<typename T>
class Graph
{
private:
	enum { zero = 0, Max = 5 };
	int vertexnum, arcnum;
	T vertex[Max];
	int arc[Max][Max];
public:
	int visited[Max] = { zero };
	Graph(T a[], int ver, int arc);
	void Depth_first_travcerse(int v);
	void Breadth_first_traverse(int v);
	void Print_adjacent(int ver, int vernum);
};
template<typename T>
Graph<T>::Graph(T a[], int ver, int arc1)
{
	vertexnum = ver;
	arcnum = arc1;
	for (int i = 0; i < vertexnum; i++)
	{
		vertex[i] = a[i];
	}
	for (int i = 0; i < vertexnum; i++)
	{
		for (int k = 0; k < vertexnum; k++)
		{
			arc[i][k] = 0;
		}
	}
	for (int i = 0; i < arcnum; i++)
	{
		int j, k;
		cout << "enter the number of two adjacent points:";
		cin >> j >> k;
		arc[j][k] = arc[k][j] = 1;
	}
}
template<typename T>
void Graph<T>::Depth_first_travcerse(int v)
{
	cout << "the vertex has:" << vertex[v] << endl;
	visited[v] = 1;
	for (int j = 0; j < vertexnum; j++)
		if (arc[v][j] == 1 && visited[j] == 0) Depth_first_travcerse(j);
}
template<typename T>
void Graph<T>::Breadth_first_traverse(int v)
{
	int Q[10];
	int front, rear;
	front = rear = -1;
	cout << "the vertex has:" << vertex[v] << endl;
	Q[++rear] = v;
	while (front != rear)
	{
		v = Q[++front];
		for (int j = 0; j < vertexnum; j++)
			if (arc[v][j] == 1 && visited[j] == 0)
			{
				cout << vertex[j];
				visited[j] = 1;
				Q[++rear] = j;
			}
	}
}
template<typename T>
void Graph<T>::Print_adjacent(int ver, int vernum)
{
	cout << "The " << ver << " vertex has adjacent to :";
	for (int i = 0; i < vernum; i++)
	{
		if (i == ver) continue;
		if (arc[ver][i] == 1) cout << vertex[i];
	}
}
int main()
{
	string vert[5] = { "v0","v1","v2","v3","v4" };
	int ver = 5, arc = 5;
	Graph<string> graph(vert, ver, arc);
	cout << "The Depth first travcerse:" << endl;
	for (int i = 0; i < ver; i++)
	{
		if (graph.visited[i] == 0)
			graph.Breadth_first_traverse(i);
	}
	for(int i=0;i<ver;i++)
		graph.visited[i] = 0;
	cout << "The Breadth_first_traverse" << endl;
		for (int i = 0; i < ver; i++)
		{
			if (graph.visited[i] == 0)
				graph.Breadth_first_traverse(i);
		}
		for (int i = 0; i<ver; i++)
			graph.visited[i] = 0;
	for (int i = 0; i < ver; i++)
		graph.Print_adjacent(i, 5);
	return 0;
}