java与python两个小人动图_用了都说好的Python、Java双实现的Graph图数据结构的定义...

这篇博客介绍了如何在Python和Java中定义一个Graph数据结构,包括Node和Edge类的详细实现。通过示例矩阵展示了如何创建和操作Graph,包括计算节点的入度和出度。
摘要由CSDN通过智能技术生成

'''

一个好用的Graph的定义

权重,from Node到to Node

weight,from ,to

[12, 2, 4];

[4, 2, 7]

....

好的定义已经帮你解决了很多问题,比如这个图的Node出度入度直接就可以求

python代码的图定义是我直接从下面的Java代码翻译过来的

'''

class Graph:

def __init__(self):

self.nodes={}

self.edges=set()

class Node:

def __init__(self,valuse):

self.valuse=valuse

self.In=0 #入度

self.out=0#出度

self.nexts=[]

self.edges=[]

class Edge:

def __init__(self,weight,From,to):

self.weight=weight

self.From=From

self.to=to

def createGraph(matrix):

graph=Graph()

for i in range(len(matrix)):

weight=matrix[i][0]

From=matrix[i][1]

to=matrix[i][2]

if(From not in graph.nodes):

graph.nodes.update({From:Node(From)})

if (to not in graph.nodes):

graph.nodes.update({to:Node(to)})

fromNode=graph.nodes.get(From)

toNode=graph.nodes.get(to)

newEdge=Edge(weight,fromNode,toNode)

fromNode.nexts.append(toNode)

fromNode.out+=1

fromNode.In+=1

fromNode.edges.append(newEdge)

graph.edges.add(newEdge)

return graph

if __name__ == '__main__':

matrix=[[1,2,3],[4,5,6]]

graph=createGraph(matrix)

print(graph.nodes.keys())

'''

## Java注释 有类型 看着方便

public class Graph {

public HashMap nodes;

public HashSet edges;

public Graph() {

nodes = new HashMap<>();

edges = new HashSet<>();

}

}

public class Node {

public int value;

public int in;

public int out;

public ArrayList nexts;

public ArrayList edges;

public Node(int value) {

this.value = value;

in = 0;

out = 0;

nexts = new ArrayList<>();

edges = new ArrayList<>();

}

}

public class Edge {

public int weight;

public Node from;

public Node to;

public Edge(int weight, Node from, Node to) {

this.weight = weight;

this.from = from;

this.to = to;

}

}

public static Graph createGraph(Integer[][] matrix) {

Graph graph = new Graph();

for (int i = 0; i < matrix.length; i++) {

Integer weight = matrix[i][0];

Integer from = matrix[i][1];

Integer to = matrix[i][2];

if (!graph.nodes.containsKey(from)) {

graph.nodes.put(from, new Node(from));

}

if (!graph.nodes.containsKey(to)) {

graph.nodes.put(to, new Node(to));

}

Node fromNode = graph.nodes.get(from);

Node toNode = graph.nodes.get(to);

Edge newEdge = new Edge(weight, fromNode, toNode);

fromNode.nexts.add(toNode);

fromNode.out++;

toNode.in++;

fromNode.edges.add(newEdge);

graph.edges.add(newEdge);

}

return graph;

}

'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值