【问题标题】:Creating adjacency matrix for BFS为 BFS 创建邻接矩阵
【发布时间】:2015-12-05 04:39:12
【问题描述】:

我得到一个包含如下数字的输入文件:

3(在图中搜索值 3)

5(图中的顶点数)

0 0(顶点0有值有0)

2(从顶点 0 开始添加 2 条边)

1(从顶点0到顶点1添加一条边)

2(从顶点0到顶点2添加一条边)

1 1(顶点 1 的值为 1)

2(从顶点 1 开始添加 2 条边)

3(从顶点1到顶点3添加一条边)

4(从顶点1到顶点4添加一条边)

2 2 (顶点 2 的值为 2).......

我想使用文件中给定的数字创建一个邻接矩阵,但我不确定如何执行此操作。我如何确保我只是用 0 或 1 填充矩阵,这取决于是否存在现有边缘?我认为我不能一个接一个地读取每个文件,因为并非所有行都详细说明了有关边缘的信息。任何见解将不胜感激。谢谢!

【问题讨论】:

    标签: c++ graph adjacency-matrix breadth-first-search


    【解决方案1】:

    由于您几乎可以立即知道矩阵的大小,因此您可以分配所需大小的邻接矩阵,然后遍历文件,在遇到边时添加边。代码大纲可能类似于:

    std::ifstream in;
    
    // Read the target and number of nodes.
    int target;
    int num_nodes;
    
    in >> target >> num_nodes;
    
    // Whatever matrix data type you are using.
    matrix adj_matrix(num_nodes, num_nodes);
    
    // Process each vertex.
    for (int i = 0; i < num_nodes; ++i) {
        int node;
        int value;
        in >> node >> value;
    
        // Figure out how many edges the vertex has.
        int num_edges;
        in >> num_edges;
    
        // Process each edge and add it to the matrix.
        for (int j = 0; j < num_edges; ++j) {
            int other_node;
            in >> other_node;
    
            // Add the dependency both ways to the matrix.
            adj_matrix[node][other_node] = true;
            adj_matrix[other_node][node] = true;
        }
    }
    

    【讨论】:

      【解决方案2】:

      假设你的矩阵 Edges 被零填充,你可以这样做:

      1. 读取第一个数字并将值存储在某处(我不 了解第一个数字的实际用途)。
      2. 读取第二个数字并将其存储在n中。
      3. 虽然第 4..8 行没有行尾
      4. 读取数字并将其存储在变量v(数字 顶点)
      5. 读取数字并将其存储在Values[v](当前值 顶点)
      6. 读取数字并将其存储在e(边数来自 v'th 顶点。
      7. 对于 i 从 1 到 e 做 8。
      8. 阅读 v1 并输入 Edges[v,v1]=1(如果 E 必须是对称的,则可能是 E[v1,v])。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多