加权图
简介
无论时加权无向图还是加权有向图都是再无向图和有向图的基础上再定义边的大小而已,这个边的大小也叫做权重,不过这个权重的含义会根据问题的描述而不同,例如两个地点间的距离用权表示就路径长度,或者两个信号塔之间通信所花的时间也可用权重来表示,表示时长。
加权的作用
举个生活中常见的例子,例如从一个地方打车另一个地方,可以有多条路径做选择,毕竟条条大路通罗马嘛,但如果需要以最快的速度到达目的地呢,那么你需要找到花费时间最少的那条路径,怎么找呢?这就可以发挥加权的作用了,可以在每条路径上标记所花时间,通过加法运算后作比较,找出花时间做少的那条路径,这也就是最短路径问题。
加权实现
顶点节点
public class VertexNode {
String vertexData;
EdgeNode firstEdge;
public VertexNode(){
}
}
边结点
public class EdgeNode {
int EdgeData;
int weight;
EdgeNode nextEdge;
public EdgeNode(){
}
}
import java.util.Scanner;
public class Graph {
private VertexNode[] headVertex;
private int numOfVertexs;
private int numOfEdges;
public Graph(){
System.out.println("请输入顶点个数:");
Scanner sc = new Scanner(System.in);
this.numOfVertexs = sc.nextInt();
System.out.println("请依次输入各个顶点:");
headVertex = new VertexNode[numOfVertexs];
for (int i = 0; i < numOfVertexs; i++) {
headVertex[i] = new VertexNode();
headVertex[i].vertexData = sc.next();
headVertex[i].firstEdge = null;
}
}
public void createGraph(){
Scanner sc = new Scanner(System.in);
System.out.println("请问你将输入几条边");
this.numOfEdges = sc.nextInt();
for (int i = 0; i < numOfEdges; i++) {
System.out.println("第" + (i+1) + "条边和权");
String v1 = sc.next();
String v2 = sc.next();
int w = sc.nextInt();
addEdge(v1, v2, w);
}
}
public void addEdge(String v1, String v2, int weight){
int i1 = getIndexByString(v1);
int i2 = getIndexByString(v2);
EdgeNode edgeNode1 = new EdgeNode();
edgeNode1.EdgeData = i2;
if(headVertex[i1].firstEdge == null){
headVertex[i1].firstEdge = edgeNode1;
edgeNode1.weight = weight;
}else{
EdgeNode eNode1 = headVertex[i1].firstEdge;
while(eNode1.nextEdge != null){
eNode1 = eNode1.nextEdge;
}
eNode1.nextEdge = edgeNode1;
eNode1.nextEdge.weight = weight;
}
}
public void showGraphWithVertex() {
System.out.println("该图的邻接表为:");
for (int i = 0; i < numOfVertexs; i++) {
System.out.print(headVertex[i].vertexData);
EdgeNode nextNode = headVertex[i].firstEdge;
while (nextNode != null) {
System.out.print("-->" + getNameOfVertexByIndex(nextNode.EdgeData)+":weight="+nextNode.weight);
nextNode = nextNode.nextEdge;
}
System.out.println();
}
}
private int getIndexByString(String v){
for (int i = 0; i < numOfVertexs; i++) {
if(v.equals(headVertex[i].vertexData)){
return i;
}
}
return -1;
}
private String getNameOfVertexByIndex(int index) {
return headVertex[index].vertexData;
}
}
测试:
public class GraphTest {
public static void main(String[] args) {
Graph graph = new Graph();
graph.createGraph();
graph.showGraphWithVertex();
}
}
结果:
请输入顶点个数:
4
请依次输入各个顶点:
A B C D
请问你将输入几条边
4
第1条边和权
A B 4
第2条边和权
A C 5
第3条边和权
A D 5
第4条边和权
B D 6
该图的邻接表为:
A-->B:weight=4-->C:weight=5-->D:weight=5
B-->D:weight=6
C
D
|