import java.util.Scanner;
public class Graph<T> {
protected final int MAXSIZE = 10;//邻接矩阵可以表示的最大的顶点数
protected final int MAX = 999;//在网中,表示没有联系(权值无限大)
protected T[] V;//顶点信息
protected int[][] arcs;//邻接矩阵
protected int e;//边数
protected int n;//顶点数
public Graph() {
V = (T[]) new Object[MAXSIZE];
arcs = new int[MAXSIZE][MAXSIZE];
}
public void CreateAdj() {//创建无向图的邻接矩阵
int i, j, k;
T v1, v2;
Scanner sc = new Scanner(System.in);
System.out.println("请输入图的顶点及边数");
System.out.println("顶点数 n=");
n = sc.nextInt();
System.out.println("边数 e=");
e = sc.nextInt();
System.out.println("请输入图的顶点信息:");
String str = sc.next();
for (i = 0; i < n; i++) {
V[i] = (T) (Object) str.charAt(i);//构造顶点信息
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
arcs[i][j] = 0;//初始化邻接矩阵
}
}
System.out.println("请输入图的边的信息:");
for (k = 0; k < e; k++) {
System.out.println("请输入第" + (k + 1) + "条边的两个顶点:");
str = sc.next();
v1 = (T) (Object) str.charAt(0);
v2 = (T) (Object) str.charAt(1);
i = LocateVex(v1);
j = LocateVex(v2);
if (i >= 0 && j >= 0) {
arcs[i][j] = 1;
arcs[j][i] = 1;
}
}
}
public int LocateVex(T v) {//在图中查找顶点v,找到之后返回其在顶点数组中的索引号,若不存在,返回—1
int i;
for (i = 0; i < n; i++)
if (V[i] == v)
return i;
return -1;
}
public void DisplayAdjMatrix() {//显示图G的邻接矩阵表示
int i, j;
System.out.println("图的邻接矩阵表示:");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(" " + arcs[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Graph<Character> G = new Graph<Character>();
G.CreateAdj();
G.DisplayAdjMatrix();
}
}
邻接矩阵(数据结构)
最新推荐文章于 2024-08-21 12:03:50 发布