图的简介
一个顶点(Vertex)可以与多个顶点连接。
邻接:两个顶点通过一条边连通。
有向图
图的代码实现
我们可以通过数组存储每个顶点,然后用邻接矩阵存储顶点之间的关系,1表示两个顶点相邻接,0表示两个顶点不邻接。
顶点类
package com.wuxudong.Graph;
//顶点类
public class Vertex {
private String value;
//布尔值来表示是否遍历
private boolean flag;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Vertex(String value){
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Vertex{" +
"value='" + value + '\'' +
'}';
}
}
图类
package com.wuxudong.Graph;
import java.util.Stack;
//图
public class Graph {
//定义数组存储数组
private Vertex [] vertices;
//定义二维数组存储节点之间的关系
private int [][] table;
//定义栈用来深度优先遍历
private Stack<Vertex> myStack=new Stack<Vertex>();
public Vertex[] getVertices() {
return vertices;
}
public void setVertices(Vertex[] vertices) {
this.vertices = vertices;
}
public int[][] getTable() {
return table;
}
public void setTable(int[][] table) {
this.table = table;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
//定义存储顶点的下标
private int index;
//定义构造方法
public Graph(int size){
vertices=new Vertex[size];
table=new int [size][size];
}
//定义添加节点的方法
public void add(Vertex vertex){
vertices[index]=vertex;
table[index][index]=1;
index++;
}
//定义添加边的方法
public void addEdge(Vertex v1,Vertex v2){
int index1=0;
for (int i=0;i<vertices.length;i++){
if (vertices[i].getValue()==v1.getValue()){
index1=i;
}
}
int index2=0;
for (int i = 0; i <vertices.length ; i++) {
if (vertices[i].getValue()==v2.getValue()){
index2=i;
}
}
table[index1][index2]=1;
table[index2][index1]=1;
}
//图的深度优先遍历
public void dls(){
//获取第一个顶点
Vertex start=vertices[0];
//打印该值
System.out.println(start.getValue());
vertices[0].setFlag(true);
//将这个顶点压入到栈
myStack.push(start);
int index=0;
//循环遍历
out: while (!myStack.isEmpty()) {
for (int i = index+1; i < vertices.length; i++) {
//判断下一个节点是否连通
if (table[index][i] == 1 && vertices[i].isFlag() == false) {
System.out.println(vertices[i].getValue());
myStack.push(vertices[i]);
vertices[i].setFlag(true);
continue out;
}
}
myStack.pop();
if (!myStack.isEmpty()) {
int k = 0;
for (int j = 0; j < vertices.length; j++) {
if (vertices[j].getValue() == myStack.peek().getValue()) {
k = j;
}
}
index = k;
}
}
}
}
测试类
package com.wuxudong.Graph;
import java.util.Arrays;
public class MyGraphTest {
public static void main(String[] args) {
Graph graph=new Graph(5);
Vertex v1=new Vertex("A");
Vertex v2=new Vertex("B");
Vertex v3=new Vertex("C");
Vertex v4=new Vertex("D");
Vertex v5=new Vertex("E");
graph.add(v1);
graph.add(v2);
graph.add(v3);
graph.add(v4);
graph.add(v5);
//添加边
graph.addEdge(v1,v2);
graph.addEdge(v1,v3);
graph.addEdge(v2,v3);
graph.addEdge(v2,v4);
graph.addEdge(v2,v5);
int [][] table=graph.getTable();
for (int [] b:table){
System.out.println(Arrays.toString(b));
}
graph.dls();
}
}