图的邻接矩阵存储及其深度遍历与广度遍历实现
原理讲解视频推荐: DFS:懒猫老师的DFS介绍 BFS:懒猫老师的BFS介绍 以上视频结合动图加深理解,个人觉得非常推荐~ 原理讲解文字版
#include<iostream>
#include<queue>
using namespace std;
#define maxsize 100
int visited[maxsize] = {0};
template <class datatype>
class Graph{
public:
Graph(datatype a[], int n,int e);
~Graph(){ };
void DFS(int v);
void BFS(int v);
void GraphAdjlist();
private:
datatype vertex[maxsize];
int arc[maxsize][maxsize];
int vertex_num, arc_num;
};
template<class datatype>
Graph<datatype>::Graph(datatype a[],int n,int e)
{
vertex_num = n;
arc_num = e;
for(int i = 0;i<vertex_num;++i)
vertex[i] = a[i];
for(int i = 0;i<vertex_num;++i)
{
for(int j = 0;j<arc_num;++j)
{
arc[i][j] = 0;
}
}
for(int k = 0; k < arc_num;++k)
{
int i,j;
cout<<"请输入邻接矩阵的两个点"<<endl;
cin>>i>>j;
arc[i][j] = 1;
arc[j][i] = 1;
}
}
template<class datatype>
void Graph<datatype>::DFS(int v)
{
cout<<"当前端点为: "<<vertex[v]<<endl;
visited[v] = 1;
for(int j = 0; j < vertex_num; ++j)
{
if(arc[v][j] == 1 && visited[j] == 0)
DFS(j);
}
}
template<class datatype>
void Graph<datatype>::BFS(int v)
{
int visited[vertex_num]= {0};
queue<int> Q;
visited[v] = 1;
Q.push(v);
while(!Q.empty())
{
v = Q.front();
cout<<"当前端点为: "<<vertex[v]<<endl;
Q.pop();
for(int k = 0;k< vertex_num;++k)
{
if(visited[k] == 0 && arc[v][k] == 1)
{
visited[k] = 1;
Q.push(k);
}
}
}
}
int main()
{
char array[] = {'a','b','c','d','e','f','g'};
Graph<char> graph(array,7,10);
cout<<"/***************DFS_result:"<<endl;
graph.DFS(5);
cout<<"/***************BFS_result:"<<endl;
graph.BFS(5);
return 0;
}
|