为 BFS 创建邻接矩阵
Creating adjacency matrix for BFS
我得到一个输入文件,其中包含这样的数字:
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
充满了零,你可以做这样的事情:
- 读取第一个数字并将值存储在某个地方(我不实际上,了解第一个数字的用途(。
- 读取第二个数字并将其存储在
n
中。 - 虽然没有行尾,但行 4..8
- 读取数字并将其存储在变量
v
(数字顶点( - 读取数字并将其存储在
Values[v]
(当前值顶点( - 读取数字并将其存储在
e
(边缘数来自v
顶点。 - 对于 i 从 1 到 e 做 8。
- 读取
v1
并输入 [v,v1]=1Edges
(如果 E 必须是对称的,则可能是 E[v1,v](。
相关文章:
- 如何在C++中为表面制作邻接矩阵
- 在 c++ 中初始化邻接矩阵
- 有关邻接矩阵实现的问题
- MFC:在编辑框中表示邻接矩阵
- C++中有向无环图的邻接列表到邻接矩阵的转换
- 在C++中从距离矩阵创建索引向量的最快方法
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 如何正确接受平方加权邻接矩阵
- 创建随机邻接矩阵,每个节点具有最小'k'度
- 如何在C++中将边列表转换为邻接矩阵,其中包含连接到顶点的边数而不是一条边?
- 确定邻接矩阵是否具有周期,然后输出该周期
- 为矩阵创建动态数组,以循环迭代器命名
- 邻接矩阵构建功能用一些图崩溃
- 在线性时间内使用邻接列表创建对顶点
- 使用邻接矩阵获取给定节点的所有边缘
- 对邻接矩阵最大循环中的节点进行计数
- 图实现,使用邻接矩阵,在链接中带有自定义数据
- 在C++中向邻接矩阵的边添加代价
- 如何在c++中使用模板图类中的向量创建邻接矩阵
- 为 BFS 创建邻接矩阵