class Graph
package DataStructures.graph;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
public class Graph {
public static void main(String[] args) {
String[] vertexes = {"A","B","C","D","E"};
Graph graph = new Graph(5);
for (String v : vertexes){
graph.insertVertex(v);
}
graph.insertEdge(0,1,1);
graph.insertEdge(0,2,1);
graph.insertEdge(1,2,1);
graph.insertEdge(1,3,1);
graph.insertEdge(1,4,1);
graph.showGraph();
graph.BFS(0);
}
private ArrayList<String> vertexList;
private int[][] edges;
private int numOfEdges;
private boolean[] isVisited;
public Graph(int n) {
edges = new int[n][n];
vertexList = new ArrayList<>(n);
isVisited = new boolean[n];
}
public void BFS(int index){
ArrayDeque<Integer> queue = new ArrayDeque<>();
while (index < vertexList.size()){
if (edges[index][index] != 0 || !isVisited[index]){
queue.add(index);
System.out.print(getValueByIndex(index) + "->");
isVisited[index] = true;
}
index++;
}
System.out.println("结束");
}
public void DFS(int index){
System.out.print(getValueByIndex(index) + "->");
isVisited[index] = true;
int s = 0;
while (s < vertexList.size() && (edges[index][s] == 0 ||(edges[index][s] != 0 && isVisited[s]))){
s++;
}
if (s > vertexList.size() - 1)
return;
DFS(s);
}
public void DFS(){
for (int i = 0; i < vertexList.size(); i++) {
if (!isVisited[i]){
DFS(i);
}
}
System.out.println("结束");
}
public void insertVertex(String v){
vertexList.add(v);
}
public void insertEdge(int v1,int v2,int weight){
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
public int getNumOfVertex(){
return vertexList.size();
}
public int getNumOfEdges(){
return numOfEdges;
}
public String getValueByIndex(int i){
return vertexList.get(i);
}
public int getWeight(int v1,int v2){
return edges[v1][v2];
}
public void showGraph(){
for (int[] l : edges){
System.out.println(Arrays.toString(l));
}
System.out.println();
}
}