记录学习中写的代码,中间有参考他人的文章,文章链接如下:
(82条消息) JAVA实现图的深度优先遍历._大道之简的博客-优快云博客_java图的深度遍历
参考的这篇文章的作者代码十分简洁,比我这个菜鸡写的好很多,从中也获益匪浅,有兴趣的初学者可以看一下。
接下来是我的代码:
/**
* 数据结构 —— 图
*/
@Data
public class Graph {
/**
* 图的节点数量
*/
private int size = 0;
/**
* 图的领接矩阵
*/
public int[][] adjacencyMatrix;
/**
* 是否遍历过标志
*/
public boolean[] hasVisited;
/**
* 图的节点数据
*/
public char[] node;
/**
* 无参构造
*/
public Graph() {
}
/**
* 有参构造
*/
public Graph(char[] node) {
this.size = node.length;
initialize();
this.node = node;
}
/**
* 添加节点集合
*/
public void nodeSet(char[] node) {
this.size = node.length;
initialize();
this.node = node;
}
/**
* 初始化图
*/
public void initialize() {
this.adjacencyMatrix = new int[this.size][this.size];
this.hasVisited = new boolean[this.size];
this.node = new char[this.size];
}
/**
* 打印图
*/
public void printGraph() {
for (int i = 0; i < getSize(); i++) {
for (int j = 0; j < getSize(); j++) {
System.out.print(adjacencyMatrix[i][j] + " ");
}
System.out.println();
}
}
/**
* 增加图的边
*
* @param c1 顶点
* @param c2 顶点
*/
public void addPath(char c1, char c2) {
if (c1 == c2) {
return;
}
int v1 = -1;
int v2 = -1;
for (int i = 0; i < node.length; i++) {
if (c1 == node[i]) {
v1 = i;
}
if (c2 == node[i]) {
v2 = i;
}
}
if (v1 == -1 || v2 == -1) {
return;
} else {
adjacencyMatrix[v1][v2] = 1;
adjacencyMatrix[v2][v1] = 1;
}
}
/**
* 深度遍历
*/
public void deepTraversal(char value) {
int index = -1;
for (int i = 0; i < node.length; i++) {
if (node[i] == value){
index = i;
}
}
if (index == -1 ) {
return;
}
System.out.print(value + "----->");
hasVisited[index] = true;
for (int i = 0; i < size; i++) {
if (adjacencyMatrix[index][i] == 1 && !hasVisited[i]) {
deepTraversal(node[i]);
}
}
}
}
main方法
public class GraphMain {
public static void main(String[] args) {
Graph graph = new Graph();
graph.nodeSet(new char[]{'A', 'F', 'W', 'G', 'P', 'I', 'B', 'C', 'D'});
graph.printGraph();
System.out.println("=================");
graph.addPath('A','B');
graph.addPath('A','C');
graph.addPath('A','D');
graph.addPath('D','F');
graph.addPath('F','B');
graph.deepTraversal('A');
}
}