构建有向图的函数,同时图结构的点和边上都支持添加属性
在Java中,你可以使用HashMap作为图节点的属性容器,并使用邻接表(Adjacency List)存储图。这里是一个简单的例子:
Java
import java.util.*;class GraphNode {int id;Map<String, Object> attributes;GraphNode(int id) {this.id = id;this.attributes = new HashMap<>();}void addAttribute(String key, Object value) {attributes.put(key, value);}
}class Edge {int source;int destination;Map<String, Object> edgeAttributes;Edge(int source, int destination) {this.source = source;this.destination = destination;this.edgeAttributes = new HashMap<>();}void addEdgeAttribute(String key, Object value) {edgeAttributes.put(key, value);}
}class DirectedGraph {private List<GraphNode> nodes;private Map<Integer, List<Edge>> edges;DirectedGraph() {this.nodes = new ArrayList<>();this.edges = new HashMap<>();}void addNode(int id, String attrKey, Object attrValue) {GraphNode node = new GraphNode(id);node.addAttribute(attrKey, attrValue);nodes.add(node);}void.addEdge(int srcId, int dstId, String edgeAttrKey, Object edgeAttrValue) {if (!edges.containsKey(srcId)) {edges.put(srcId, new ArrayList<>());}Edge edge = new Edge(srcId, dstId);edge.addEdgeAttribute(edgeAttrKey, edgeAttrValue);edges.get(srcId).add(edge);}
}
在Python中,我们可以使用字典(dict)来表示节点和边的属性。这里是相应的实现:
Python
class Node:def __init__(self, id):self.id = idself.attributes = {}# 添加属性方法def add_attribute(self, key, value):self.attributes[key] = valueclass Edge:def __init__(self, source, destination):self.source = sourceself.destination = destinationself.edge_attributes = {}# 添加属性方法def add_edge_attribute(self, key, value):self.edge_attributes[key] = valueclass Graph:def __init__(self):self.nodes = []self.edges = {}# 添加节点和边的示例def add_node(self, id, attr_key, attr_value):node = Node(id)node.add_attribute(attr_key, attr_value)self.nodes.append(node)def add_edge(self, src_id, dst_id, edge_attr_key, edge_attr_value):if src_id not in self.edges:self.edges[src_id] = []edge = Edge(src_id, dst_id)edge.add_edge_attribute(edge_attr_key, edge_attr_value)self.edges[src_id].append(edge)# 使用示例
graph = Graph()
graph.add_node(1, 'attr', 'value')
graph.add_edge(1, 2, 'edge_attr', 'value')
在C语言中,由于原生数据结构没有直接对应于Python或Java的灵活性,可以使用结构体和链表来实现。这里给出一个简化的版本:C
#include <stdio.h>
#include <stdlib.h>typedef struct Node {int id;char *attributes;
} Node;typedef struct Edge {int source;int destination;char *edge_attributes;
} Edge;typedef struct Graph {Node **nodes;int *edges;size_t num_nodes;size_t num_edges;
} Graph;
void add_node(Graph *g, int id, const char *attr_key, const char *attr_value) {
}void add_edge(Graph *g, int src_id, int dst_id, const char *edge_attr_key, const char *edge_attr_value) {
}int main() {Graph graph;return 0;
}