广度优先遍历

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)
{
@ -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)
{
@ -154,6 +158,7 @@ public:
V[id2]->inDegree--;
delete E[id1][id2];
E[id1][id2] = NULL;
e--;
return 0;
@ -183,7 +188,6 @@ public:
std::cout << std::setw(14) << E[i][j]->weight;
else
std::cout << std::setw(14) << "-";
}
printf("\n");
}
@ -191,8 +195,12 @@ public:
virtual void BFS(int id)
{
Queue<int> q;
reset();
if(V[id]==NULL)
return;
Queue<int> q;
V[id]->status = DISCOVERED;
q.enqueue(id);
while (!q.empty())
{
@ -200,13 +208,31 @@ public:
for (int j = 0; j < 100; j++)
{
if(E[id][j]!=NULL)
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());
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;
}
}
}
};