十一、图的存储---(3)邻接矩阵的构造和使用

摘自计蒜客:http://www.jisuanke.com/course/35/7195

//以下主要针对有向图,如果遇到无向图的情况,将每条无向边对应到有向图中的正反两条边就可以了。


#include <iostream>
#include <cstring>
using namespace std;

class Graph {
private:
    int **mat;
    int n;

public:
    Graph(int input_n) {
        n = input_n;
        mat = new int*[n];
        for (int i = 0; i < n; ++i) {
            mat[i] = new int[n];
            memset(mat[i], 0, sizeof(int) * n);
        }
    }

    ~Graph() {
        for (int i = 0; i< n; ++i) {
            delete[] mat[i];
        }
        delete[] mat;
    }

    void insert(int x, int y) {
        mat[x][y] = 1;
    }

    void output() {
        for (int i=0; i<n; i++) {
            for (int j=0; j<n; j++) {
                cout << mat[i][j] << " ";
            }
            cout << endl;
        }
    }
};

int main() {
    int n, m, x, y;
    cin >> n >> m;
    Graph g(n);
    for (int i = 0; i < m; ++i) {
        cin >> x >> y;
        g.insert(x, y);
    }
    g.output();
    return 0;
}


### 构建邻接矩阵特征矩阵 #### 邻接矩阵的构建方法 在论中,邻接矩阵是一种表示的方式。对于一个具有 \( n \) 个顶点的无向,其邻接矩阵是一个 \( n \times n \) 的方阵 \( A \),其中元素 \( a_{ij} \) 表示节点 \( i \) 节点 \( j \) 是否存在边连接。 如果采用阈值约束生成邻接矩阵,则可以根据特定条件设定相邻关系[^2]: - 如果两个节点之间的相似度或距离满足某个预定义的阈值,则认为这两个节点之间有边相连; - 否则,认为这两者不直接相连; 这种基于阈值的方法可以有效地控制中的连通性稀疏性,从而影响后续算法的表现。 ```python import numpy as np def create_adj_matrix(similarity_matrix, threshold): adj_matrix = (similarity_matrix >= threshold).astype(int) np.fill_diagonal(adj_matrix, 0) # Remove self-loops return adj_matrix ``` #### 特征矩阵的构建方式 特征矩阵通常用来存储每个节点的相关属性信息,在机器学习应用中尤为重要。假设有一个包含 \( m \) 种不同类型的特性数据集,那么该对应的特征矩阵就是一个大小为 \( n \times m \) 的二维数组 \( X \)[^4]。 每一行代表一个单独的数据样本(即的一个结点),而列数对应于所选特征的数量。这些特征可能来自于原始输入资料本身或者是通过某种转换过程得到的新变量。 例如,在社交网络分析场景下,用户的年龄、性别以及兴趣爱好都可以作为有效的节点特征加入到矩阵当中去。 ```python # Example of creating feature matrix from node attributes node_attributes = [ {&#39;age&#39;: 25, &#39;gender&#39;: &#39;male&#39;, &#39;interests&#39;: [&#39;sports&#39;]}, {&#39;age&#39;: 30, &#39;gender&#39;: &#39;female&#39;, &#39;interests&#39;: [&#39;music&#39;]} ] feature_names = list(node_attributes[0].keys()) num_features = len(feature_names) features = [] for attr_dict in node_attributes: row = [attr_dict[name] for name in feature_names] features.append(row) X = np.array(features) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值