#include <iostream>
#include <queue>
using namespace std;
bool cmp[100];
queue<int>Myqueue;
struct Node //链表结构
{
int vex;
int weight;
Node* next;
};
typedef struct Hnode //头结构
{
char data; //节点数据
Node* head;
}*List;
typedef struct GNode
{
int vexnum;//节点数目
int arcnum;//边数
List list;
}*Graph;
Graph CreatGraph();
void dfs(Graph graph, int k);
void dfsreverse(Graph graph);
void bfs(Graph graph, int k);
void bfsreverse(Graph graph);
//void printGraph(Graph graph);
int main()
{
Graph graph=CreatGraph();
cout << "深度优先遍历:\n";
dfsreverse(graph);
cout << "\n广度优先遍历:\n";
bfsreverse(graph);
cout << "\n邻接表转邻接矩阵大法:\n";
printGraph(graph);
return 0;
}
Graph CreatGraph()
{
Graph graph = new GNode;
cout << "请输入顶点个数和边数:\n";
cin >> graph->vexnum >> graph->arcnum;
graph->list = new Hnode[graph->vexnum+1];
cout << "请输入每个顶点的数据:\n";
for (int i = 1; i <= graph->vexnum; i++)
{
cin >> graph->list[i].data;
graph->list[i].head = nullptr;//初始化
}
cout << "请输入边的起点,终点以及权重大小\n";
for (int i = 1; i <= graph->arcnum; i++)
{//使用头插法并且是无向图
int begin, end, value;
cin >> begin >> end >> value;
Node* node = new Node;
node->vex = end;
node->weight = value;
node->next = graph->list[begin].head;
graph->list[begin].head = node;
//因为是无向图,所以还要进行一次反向链接操作。
node = new Node;
node->vex = begin;
node->weight = value;
node->next = graph->list[end].head;
graph->list[end].head = node;
}
return graph;
}
void dfs(Graph graph,int k)
{
cmp[k] = true;
cout << graph->list[k].data << " ";
Node* pMove = graph->list[k].head;
while (pMove)
{
if (!cmp[pMove->vex])dfs(graph, pMove->vex);
pMove = pMove->next;
}
}
void dfsreverse(Graph graph)//对每个节点进行判断
{
for (int i = 1; i <= graph->vexnum; i++)
{
if (!cmp[i])dfs(graph, i);
}
}
void bfs(Graph graph, int k)
{
cmp[k] = true;
cout << graph->list[k].data << " ";
Myqueue.push(k);
while (!Myqueue.empty())
{
int top = Myqueue.front();
Myqueue.pop();
Node* pMove = graph->list[top].head;
while (pMove)
{
if (!cmp[pMove->vex])
{
cmp[pMove->vex] = true;
cout << graph->list[pMove->vex].data << " ";
Myqueue.push(pMove->vex);
}
pMove = pMove->next;
}
}
}
void bfsreverse(Graph graph)//对每个节点进行判断
{
for (int i = 1; i <= graph->vexnum; i++)
cmp[i] = 0;
for (int i = 1; i <= graph->vexnum; i++)
{
if (!cmp[i])bfs(graph, i);
}
}
图的DFS/BFS遍历,简易易懂
最新推荐文章于 2024-08-27 13:29:10 发布