广度优先遍历

This commit is contained in:
iridiumR 2021-12-17 15:37:48 +08:00
parent 686b0a90ff
commit c547c71d05
3 changed files with 52 additions and 20 deletions

View File

@ -109,7 +109,7 @@ template <class T>
T List<T>::remove(listNode p)
{
if (!_size)
return NULL;
return 0;
T temp = p->data;
(p->pred)->succ = p->succ;

View File

@ -14,7 +14,7 @@ int main()
std::string name;
while (1)
{
printf("选择操作:1添加/覆盖节点2添加边3删除节点4删除边5显示图\n");
printf("选择操作:1添加/覆盖节点2添加边3删除节点4删除边5显示图6广度优先遍历\n");
scanf("%d", &op);
switch (op)
{
@ -26,7 +26,7 @@ int main()
case 2:
printf("分别输入起始节点序号 到达节点序号 边权重:");
std::cin >> id1 >> id2 >> w;
if(id1==id2)
if (id1 == id2)
printf("失败\n");
switch (gv.link(id1, id2, w))
{
@ -64,6 +64,12 @@ int main()
break;
case 5:
gv.display();
break;
case 6:
printf("输入起始节点序号:");
std::cin >> id1;
gv.BFS(id1);
break;
default:
break;
}

View File

@ -1,11 +1,13 @@
#ifndef _graph_hpp_
#define _graph_hpp_
#include "../ex10/queue.hpp"
#include "vector.hpp"
#include <iomanip>
#include <iostream>
#include <string>
#include "../ex10/queue.hpp"
#define DISCOVERED 1
#define UNDISCOVERED 0
#define VISITED 2
template <class Te>
class Edge
@ -36,11 +38,13 @@ public:
Tv data;
int inDegree;
int outDegree;
int status;
Vertex()
{
// data = NULL;
inDegree = 0;
outDegree = 0;
status = UNDISCOVERED;
}
Vertex(Tv d)
{
@ -56,7 +60,7 @@ class graphVertex
private:
Vector<Vertex<Tv> *> V;
Edge<Te> *E[100][100] = {NULL};
int v;
int e;
@ -101,7 +105,7 @@ public:
}
virtual Tv remove(int id)
{
if(V[id]==NULL)
if (V[id] == NULL)
return (Tv)0;
for (int j = 0; j < v; j++)
{
@ -134,7 +138,7 @@ public:
V[id2]->inDegree++;
e++;
Edge<Te> *temp = new Edge<Te>(w);
E[id1][id2]= temp;
E[id1][id2] = temp;
return 0;
}
// 解除 id1->id2 连接
@ -154,13 +158,14 @@ public:
V[id2]->inDegree--;
delete E[id1][id2];
E[id1][id2] = NULL;
e--;
return 0;
}
virtual void display()
{
{
// std::cout << std::setw(14) << temp->weight;
//第一行
std::cout << std::left << std::setw(14) << " ";
@ -168,7 +173,7 @@ public:
if (V[i] != NULL)
std::cout << std::setw(4) << i << std::setw(10) << V[i]->data;
printf("\n");
for (int i = 0; i < V._len; i++)
if (V[i] != NULL)
{
@ -183,7 +188,6 @@ public:
std::cout << std::setw(14) << E[i][j]->weight;
else
std::cout << std::setw(14) << "-";
}
printf("\n");
}
@ -191,22 +195,44 @@ public:
virtual void BFS(int id)
{
reset();
if(V[id]==NULL)
return;
Queue<int> q;
V[id]->status = DISCOVERED;
q.enqueue(id);
while (!q.empty())
{
int vid = q.dequeue();
int vid = q.dequeue();
for (int j = 0; j < 100;j++)
{
if(E[id][j]!=NULL)
q.enqueue(j);
}
for (int j = 0; j < 100; j++)
{
if (E[vid][j] != NULL)
{
if (V[j]->status == UNDISCOVERED)
{
q.enqueue(j);
V[j]->status = DISCOVERED;
}
}
}
// std::cout << node->pos;
printf("ID: %d",q.dequeue());
// std::cout << node->pos;
printf("VISIT ID: %d \n", vid);
V[vid]->status = VISITED;
}
}
void reset()
{
for (int j = 0; j < V._len; j++)
{
if (V[j] != NULL)
{
V[j]->status = UNDISCOVERED;
}
}
}
};