c++建立图的邻接矩阵
时间: 2023-10-20 08:28:48 浏览: 80
在C++中,我们可以使用二维数组来表示图的邻接矩阵。其中,每个元素表示两个顶点之间是否有边相连,如果相连则为1,否则为0。
以下是一个简单的示例代码:
```c++
const int MAXN = 100; // 最大顶点数
int G[MAXN][MAXN]; // 邻接矩阵
int main() {
int n, m; // n为顶点数,m为边数
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v; // u和v分别为一条边的两个端点
cin >> u >> v;
G[u][v] = G[v][u] = 1; // 无向图需要将两个方向都设置为1
}
return 0;
}
```
其中,输入的第一行为顶点数n和边数m,接下来m行为每条边的两个端点u和v。在处理边的时候,需要将G[u][v]和G[v][u]都设置为1,因为无向图中的一条边对应着两个方向。
相关问题
c++输出地图邻接矩阵
假设地图中有n个点,我们可以使用一个n*n的矩阵来表示它们之间的连接关系。如果两个点之间有连接,则在矩阵中对应位置上的值为1,否则为0。下面是一个简单的C++程序,用于输出地图的邻接矩阵:
```c++
#include <iostream>
using namespace std;
const int MAXN = 100;
int map[MAXN][MAXN]; // 定义地图的邻接矩阵
int main()
{
int n; // 地图中的点数
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> map[i][j]; // 输入地图的邻接矩阵
// 输出地图的邻接矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << map[i][j] << " ";
cout << endl;
}
return 0;
}
```
在这个程序中,我们通过一个二维数组`map`来存储地图的邻接矩阵,然后通过两个嵌套的循环遍历这个数组,输出每一个元素的值。注意,在输入地图的邻接矩阵时,我们也是通过两个嵌套的循环来完成的。
c++图采用邻接矩阵或者邻接表创建一个如图1所示的无向网
在C++中创建一个如图1所示的无向网络,我们可以选择使用邻接矩阵或邻接表这两种数据结构。
**1. 邻接矩阵:**
邻接矩阵是一个二维数组,其中行代表起点,列表示终点,值表示连接状态。如果两个节点之间有边,则对应位置的值为1或true(对于布尔型),否则为0或false。对于无向图,由于无向边是双向的,所以对称的位置也需要存储相同的值。
```cpp
typedef bool EdgeType;
vector<vector<EdgeType>> adjacencyMatrix; // 使用std::vector表示
adjacencyMatrix.resize(numVertices); // 初始化为numVertices×numVertices的矩阵
// 添加边 (u, v)
adjacencyMatrix[u][v] = true; // 如果(u, v)存在则设置为true
adjacencyMatrix[v][u] = true; // 对于无向图,添加(v, u)
```
**2. 邻接表:**
邻接表则是通过链表或哈希表来表示每个节点的邻居。每个节点都有一个链表或哈希表,存储所有与其相连的其他节点。这样空间效率较高,特别是当图中大部分节点度数不高时。
```cpp
struct Node {
int index;
vector<int> neighbors; // 存储邻居节点的索引
};
Node* nodes[numVertices]; // 或使用vector<Node*>代替
for (int i = 0; i < numVertices; ++i) {
nodes[i] = new Node{i};
}
// 添加边 (u, v)
nodes[u].neighbors.push_back(v);
nodes[v].neighbors.push_back(u); // 无向图中添加对方到对方节点的引用
```
阅读全文
相关推荐
















