深度优先遍历
package tu;
import java.util.ArrayList;
import java.util.Arrays;
public class Graph {
private ArrayList<String> veryextlist;
// 顶点元素
private int[][] edges;
// 描述邻接矩阵的
private int edgesNum;
// 边的数量
private boolean[] isSelected;
// 是否被选中
public Graph(int x) {
// 描述顶点的个数
this.veryextlist=new ArrayList<>(x);
this.edges=new int[x][x];
this.isSelected=new boolean[x];
}
/**
* 插入顶点的方法
*/
public void insertVertex(String vertex){
this.veryextlist.add(vertex);
}
/**
* 添加图的边
*/
public void insertEdges(int x,int y,int w){
// 添加边
edges[x][y]=w;
edges[y][x]=w;
// 添加边的数量
this.edgesNum++;
}
/**
* 返回顶点的个数
*/
public int getVertexNum(){
return this.veryextlist.size();
}
//返回边的数量
public int getEdgesSize(){
return this.edgesNum;
}
/**
* 回去顶点的权值,x y坐标下的权值
*/
public int getWeight(int x, int y){
return this.edges[x][y];
}
/**
* 输出邻接矩阵的图案,遍历数组
*/
public void showList(){
for (int[] array : edges){
System.out.println(Arrays.toString(array));
}
}
}
class Testone{
public static void main(String[] args) {
String[] vertexs={"A","B","C","D","E"};
Graph graph = new Graph(5);
for (String v:vertexs){
graph.insertVertex(v);
}
graph.insertEdges(0,1,1);
graph.insertEdges(0,2,1);
graph.insertEdges(1,2,1);
graph.insertEdges(1,3,1);
graph.insertEdges(1,4,1);
graph.showList();
}
}
运行结果
[0, 1, 1, 0, 0]
[1, 0, 1, 1, 1]
[1, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]