为 BFS 创建邻接矩阵

Creating adjacency matrix for BFS

本文关键字:邻接矩阵 创建 BFS      更新时间:2023-10-16

我得到一个输入文件,其中包含这样的数字:

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 填充矩阵,具体取决于是否存在现有的边?我不认为我可以逐个阅读每个文件,因为并非所有行都详细介绍了有关边缘的信息。任何见解将不胜感激。谢谢!

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

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;
    }
}

假设你的矩阵Edges充满了零,你可以做这样的事情:

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