广度优先遍历

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) T List<T>::remove(listNode p)
{ {
if (!_size) if (!_size)
return NULL; return 0;
T temp = p->data; T temp = p->data;
(p->pred)->succ = p->succ; (p->pred)->succ = p->succ;

View file

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

View file

@ -1,11 +1,13 @@
#ifndef _graph_hpp_ #ifndef _graph_hpp_
#define _graph_hpp_ #define _graph_hpp_
#include "../ex10/queue.hpp"
#include "vector.hpp" #include "vector.hpp"
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <string> #include <string>
#include "../ex10/queue.hpp" #define DISCOVERED 1
#define UNDISCOVERED 0
#define VISITED 2
template <class Te> template <class Te>
class Edge class Edge
@ -36,11 +38,13 @@ public:
Tv data; Tv data;
int inDegree; int inDegree;
int outDegree; int outDegree;
int status;
Vertex() Vertex()
{ {
// data = NULL; // data = NULL;
inDegree = 0; inDegree = 0;
outDegree = 0; outDegree = 0;
status = UNDISCOVERED;
} }
Vertex(Tv d) Vertex(Tv d)
{ {
@ -154,6 +158,7 @@ public:
V[id2]->inDegree--; V[id2]->inDegree--;
delete E[id1][id2]; delete E[id1][id2];
E[id1][id2] = NULL;
e--; e--;
return 0; return 0;
@ -183,7 +188,6 @@ public:
std::cout << std::setw(14) << E[i][j]->weight; std::cout << std::setw(14) << E[i][j]->weight;
else else
std::cout << std::setw(14) << "-"; std::cout << std::setw(14) << "-";
} }
printf("\n"); printf("\n");
} }
@ -191,8 +195,12 @@ public:
virtual void BFS(int id) virtual void BFS(int id)
{ {
Queue<int> q; reset();
if(V[id]==NULL)
return;
Queue<int> q;
V[id]->status = DISCOVERED;
q.enqueue(id); q.enqueue(id);
while (!q.empty()) while (!q.empty())
{ {
@ -200,13 +208,31 @@ public:
for (int j = 0; j < 100; j++) 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); q.enqueue(j);
V[j]->status = DISCOVERED;
}
}
} }
// std::cout << node->pos; // 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;
}
} }
} }
}; };