邻接矩阵构建
package Graph;
import java.util.Scanner;
//邻接矩阵结构及构造
class MGraph {
int vex[] = new int[1000]; //顶点表
int arc[][] = new int[1000][1000]; //邻接矩阵(边表)
int vexnum, arcnum; //顶点数和边数
}
public class Adjacency_Matrix {
public static void createMGraph (MGraph mGraph) {
System.out.println("请输入顶点数和边数");
Scanner sc = new Scanner(System.in);
mGraph.vexnum = sc.nextInt();
mGraph.arcnum = sc.nextInt();
System.out.println("请输入顶点");
for(int i = 0; i < mGraph.vexnum; i++) {
mGraph.vex[i] = sc.nextInt();
}
//初始化邻接矩阵
for(int i = 1; i < mGraph.vexnum; i++) {
for(int j = 0; j < mGraph.vexnum; j++) {
if(i == j) {
mGraph.arc[i][j] = 0;
}else {
mGraph.arc[i][j] = Integer.MAX_VALUE;
}
}
}
//这里注意顶点有可能是从1开始的,那么邻接矩阵也是从索引1开始
System.out.println("请输入边的坐标以及权值");
for(int i = 0; i < mGraph.arcnum; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
//有向图
mGraph.arc[x][y] = sc.nextInt();
//无向图
// mGraph.arc[x][y] = mGraph.arc[y][x] = sc.nextInt();
}
}
public static void main(String[] args) {
MGraph mGraph = new MGraph();
createMGraph(mGraph);
}
}
邻接表构建
package Graph;
import java.util.Scanner;
//邻接点
class EdgeNode {
int node; //邻接点下标
int w; // 权重
EdgeNode next;
EdgeNode(int node, int w, EdgeNode next) {
this.node = node;
this.w = w;
this.next = next;
}
}
//顶点
class VNode {
int node;
EdgeNode next;
VNode(int node, EdgeNode next) {
this.node = node;
this.next = next;
}
}
public class Adjacency_table {
static int vexnum, arcnum;
public static void createGraph(VNode[] vNode) {
System.out.println("请输入节点数和边数");
Scanner sc = new Scanner(System.in);
vexnum = sc.nextInt();
arcnum = sc.nextInt();
System.out.println("请输入顶点信息");
for(int i = 1; i <= vexnum; i++) {
VNode vNode1 = new VNode(sc.nextInt(), null);
vNode[i] = vNode1;
}
//这里只考虑有向图,用头插法
System.out.println("请输入顶点坐标(x, y)以及权重");
for(int i = 1; i <= arcnum; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
int w = sc.nextInt();
EdgeNode edgeNode = new EdgeNode(y, w, null);
//头插法
edgeNode.next = vNode[x].next;
vNode[x].next = edgeNode;
}
}
public static void main(String[] args) {
VNode[] vNode = new VNode[1000];
createGraph(vNode);
System.out.println("over");
}
}
参考文献:
https://blog.csdn.net/jnu_simba/article/details/8866705
https://blog.csdn.net/bubaxiu/article/details/39529451