本人csdn常客,不怎么发文章,今天第一次发,下面是我写的关于bfs和dfs的代码,需要的自取,原理我不讲,程序所用语言为c++,其中代码中深度优先被我注释掉了,需要深度优先的复制被注释的代码即可
#include
#include
#include
#include
using namespace std;
struct MapPoint {
string PointName;
vector index;
int piontindex;
};
/void dfsfind(int havefind,MapPoint pointline, int(point1)[100], int number, int i) {
if (havefind[i] == 1)
return;
havefind[i] = 1;cout << pointline[i].piontindex<<“号点:”<< pointline[i].PointName << “->” << endl;
for (int k = 0;k < number;k++) {
if (point1[i][k])
{
find(havefind,pointline, point1, number, k);
}
}
}/
void add(queue bfspoint, int havefind, MapPoint pointline, int(point1)[100], int number, int i) {
bfspoint->push(pointline[i]);havefind[i] = 1;
}
void bfsfind(queue bfspoint, int* havefind, MapPoint* pointline, int(point1)[100], int number, int i) {
bfspoint->push(pointline[0]);havefind[0] = 1;cout << pointline[0].piontindex << “号点” << pointline[0].PointName << “->” << endl;
while (!bfspoint->empty())
{
for (int j = 0;j < bfspoint->size();j++) {
for (int k = 0;k < number;k++) {
if (point1[bfspoint->front().piontindex - 1][k] && !havefind[k])
{
add(bfspoint, havefind, pointline, point1, number, k);
cout << pointline[k].piontindex << “号点” << pointline[k].PointName << “->” << endl;
}
}
bfspoint->pop();
}
}
}
void main()
{
cout << “请输入图的点数” << endl;
int number;
cin >> number;
MapPoint pointline[100];
int m;
cout << “请输入点的名字,以及它的点号和邻接点号” << endl;
for (int i = 0;i < number;i++) {
MapPoint k = new MapPoint;
cin >> k->PointName;
cin >> k->piontindex;
pointline[i] = *k;
}
int(*point1)[100] = new int[100][100];
for (int i = 0;i < number;i++)
{
for (int j = 0;j < number;j++) {
cin >> point1[i][j];
}
}
int havefind[100] = {0,0};
queue bfspoint[100];
//dfsfind(havefind, pointline, point1, number, 0);
bfsfind(bfspoint, havefind, pointline, point1, number, 0);
}