【问题标题】:Creating Undirected Graph With Correct Edges创建具有正确边的无向图
【发布时间】:2015-12-21 04:40:45
【问题描述】:

您好,我正在创建 100 个用于测试 dijkstra 算法的图表。我检查以确保连接的两个随机生成的节点号不相同。但是我不明白如何检查一对是否已经存在,以便在两个节点之间出现多个边缘。如何防止两个节点之间出现两条边?

void mapDataGenerator(int start, int end, int iterations,
                        int *pathCount, int *weightCount, int *timeCount)
{
int nodeCount = rand() % 8128 + 64;
edgeListTemplate edgeList(nodeCount);
//cout << "The node count is: " << nodeCount;
int n = 0;
list<vertex_v> path;
vector<weight_w> min_distance;
vector<vertex_v> previous;


while (n != nodeCount)
{

    int nodeNumb = (rand() % nodeCount); // Generates a possible node 1 
    int nodeDest = (rand() % nodeCount); // Generates a possible node 2

    //cout << "The node connection 1 is: " << nodeNumb << endl;
    //cout << "The node connection 2 is: " << nodeDest << endl;
    int node_weight = rand() % 5 + 1; // Generate random weight of node

    //cout << "The node weight is: " << node_weight << endl;

    // Create adjacency list
    if (nodeNumb != nodeDest) // if the random nodes generated are not same
    {
        edgeList[nodeNumb].push_back(node(nodeDest, node_weight));
        // For undirected graph create opposite connection back 
        edgeList[nodeDest].push_back(node(nodeNumb, node_weight));
        ++n;
    }
  }

【问题讨论】:

  • 我不确定为什么有人会赞成这个问题,但显然你必须检查边缘是否存在......
  • 这是我的问题,如何检查边缘是否存在?

标签: c++ graph nodes dijkstra


【解决方案1】:

您可以简单地使用 map/set 数据结构来跟踪已经存在的边缘。精确的配对地图就可以完成这项工作。

代码

// map declaration
map<pair<int, int>, bool> M;

if (nodeNumb != nodeDest && !M.count(make_pair(nodeNumb, nodeDest))) // if the random nodes generated are not same
{
     // Marking the pair of edges
     M[make_pair(nodeNumb, nodeDest)] = true;
     edgeList[nodeNumb].push_back(node(nodeDest, node_weight));
     // For undirected graph create opposite connection back 
     edgeList[nodeDest].push_back(node(nodeNumb, node_weight));
     ++n;
 }

【讨论】:

  • 谢谢你,这是一个很好的解决方案。
  • 哦,你们两个正在提升。
  • 只是因为我无法对问题添加评论,所以我添加了答案。
猜你喜欢
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多