16.图
构造上图的图
public class Graph {
//定点集合
private List<String> vertexList;
//存储图对应的临结矩阵
private int[][] edges;
//表示边的数目
private int numOfEdges;
public static void main(String[] args) {
String[] arr = {"A", "B", "C", "D", "E"};
Graph graph = new Graph(arr.length);
for (String value : arr) {
graph.insertVertex(value);
}
//插入边:A-C A-B C-B B-E B-D 总计5条边
graph.insertEdge(graph.getIndex("A"), graph.getIndex("C"), 1);
graph.insertEdge(graph.getIndex("A"), graph.getIndex("B"), 1);
graph.insertEdge(graph.getIndex("B"), graph.getIndex("C"), 1);
graph.insertEdge(graph.getIndex("B"), graph.getIndex("E"), 1);
graph.insertEdge(graph.getIndex("B"), graph.getIndex("D"), 1);
graph.show();
}
public void show() {
System.out.println(" "+vertexList);
int i=0;
for (int[] colum : edges) {
System.out.print(vertexList.get(i++)+" ");
System.out.println(Arrays.toString(colum));
}
System.out.println("边的数量:"+numOfEdges);
}
/**
* @param n 有几个节点
*/
public Graph(int n) {
this.vertexList = new ArrayList<>(n);
this.edges = new int[n][n];
}
public int getIndex(String vertex) {
return vertexList.indexOf(vertex);
}
/**
* 插入节点
*
* @param vertex
*/
public void insertVertex(String vertex) {
vertexList.add(vertex);
}
/**
* 插入边
*
* @param v1 节点对应的数字下标
* @param v2 节点对应的数字下标
* @param weight 权值,0代表不连接, 1代表连接
*/
public void insertEdge(int v1, int v2, int weight) {
//因为是无向图,所以正反都得赋值
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
}
输出:
[A, B, C, D, E]
A [0, 1, 1, 0, 0]
B [1, 0, 1, 1, 1]
C [1, 1, 0, 0, 0]
D [0, 1, 0, 0, 0]
E [0, 1, 0, 0, 0]
边的数量:5
图的深度优先遍历
图的广度优先遍历,太烦了,没看!!!