【发布时间】:2020-04-10 17:14:42
【问题描述】:
我需要以矩阵形式实现以下代码。我需要获取源顶点并随机生成连通图。但是,伪代码采用列表形式,我不确定我是否将其正确转换为矩阵形式,出于某种原因,我不断让所有节点得到充分探索,或者它们的颜色全部变为黑色?
D代表距离
π 代表父母
颜色 = 白色未访问/灰色已访问/黑色所有邻居已探索
#include <iostream>
#include <limits>
#include <queue>
#include <stdlib.h> /* srand, rand */
using namespace std;
enum Color {white , gray, black};
struct vertex{
Color color =white ;
int relationship =0;
int distance =abs(numeric_limits<int>::max());
int parent =0;
};
void BFS(int size ,int s)
{
//no need for first loop to initializer to defaults since they are already
vertex g [size][size];
int random;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
random =rand()%(size);
if(j!=i and random!=i) //to make it undirected
{
g[i][random].relationship=1;
g[random][i].relationship=1;
}
}
}
///
g[s][0].color =gray;
g[s][0].distance=0;
g[s][0].parent=0;
queue <int> q;
q.push(s);
int u;
while(!q.empty())
{
u=q.front();
q.pop();
g[u][0].color=black;
for(int v=0;v<size;v++)
{
if (g[u][v].relationship==1 and g[v][0].color==white) {
g[v][0].color = gray;
g[v][0].distance = g[u][0].distance+1;
g[v][0].parent = u;
q.push(v);
}
}
}
for(int i = 0; i<size;i++)
{
for(int j =0;j<size;j++)
{
cout<<g[i][j].relationship <<" ";
}
cout<<endl;
}
for(int i = 0; i<size;i++)
{
cout<<" Distance of node: " << i<<" from the source is: ";
cout<< g[i][0].distance<<" ";
if(g[i][0].color==white)
{
cout<<" Color of node: " << i<<" is white";
}
if(g[i][0].color==gray)
{
cout<<" Color of node: " << i<<" is gray";
}
if(g[i][0].color==black){
cout<<" Color of node: " << i<<" is black";
}
cout<<" parent of node: " << i<<" ";
cout<< g[i][0].parent<<" "<<" ";
cout<<endl;
}
}
int main() {
int vertices;
cout<<"Please enter the number of vertices: "<<endl;
cin>>vertices;
int source;
cout<<"Please enter the source "<<endl;
cin>>source;
BFS(vertices,source);
return 0;
}
【问题讨论】:
-
如果它是无向的,不应该是 g[i][j].relationship=1 AND g[j][i].relationship=1 吗?还是你的意思是别的?
-
无向图的对角矩阵应为0,否则有向
-
我写的是 I 和 J,而不是 I 和 I。你写的是无向的。这意味着如果 g[ I ][ J ] 关系存在,则 g[ J ][ I ] 也存在。你似乎也没有在 BFS 稍后检查 g[U][V] 和 g[V][U],你也没有在设置时设置 g[ I ][ J ] 和 g[ J ][ I ] g[ I ][ J ] 在生成随机边的部分。
-
@JunisvaultCo 哦,我明白了,谢谢!
标签: c++ algorithm graph-algorithm breadth-first-search clrs