图的构造

包含一个存有所有节点和编号的HashMap

和一个存有所有边的 HashSet

public class Graph {
	public HashMap<Integer,Node> nodes;//所有的节点,和节点编号。
	public HashSet<Edge> edges;//所有的边

	public Graph() {
		nodes = new HashMap<Integer,Node>();
		edges = new HashSet<Edge>();
	}
}

weight 代表 一条边的权值

from 开始的节点

to 边指向的节点

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;
	}

}

顶点

in代表他的入度

out 代表他的出度

nexts 代表所有已本节点为出度的邻居节点

edges 代表所有已本节点为出度的边

public class Node {
	public int value;
	public int in;//入度
	public int out;//出度
	public ArrayList<Node> nexts;//下一级的邻居
	public ArrayList<Edge> edges;//有关系的边

	public Node(int value) {
		this.value = value;
		in = 0;
		out = 0;
		nexts = new ArrayList<Node>();
		edges = new ArrayList<Edge>();
	}
}

在面试时,面试官经常给的图一般是
[
[7,1,2]

[5,1,3]

[4,2,6]

]

一个二维数组,代表,

开始节点为1,结束节点为2的权值为7的一条边

开始节点为1,结束节点为3的权值为5的一条边

开始节点为2,结束节点为2的权值为6的一条边


需要转换一下

	public static Graph createGraph(Integer[][] matrix) {
		Graph graph = new Graph();
		for (int i = 0; i < matrix.length; i++) {
			Integer from = matrix[i][0];
			Integer to = matrix[i][1];
			Integer weight = 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;
	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SUNbrightness

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值