import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Graph {
private ArrayList<String> vertexList;
private int[][] edges;
private int numOfEdges;
private boolean[] isVisited;
public Graph(int n) {
this.vertexList = new ArrayList<>(n);
this.edges = new int[n][n];
this.numOfEdges = 0;
}
public static void main(String[] args) {
int n = 8;
String[] vertexs = {"1", "2", "3", "4", "5", "6", "7", "8"};
Graph graph = new Graph(n);
for (String vertex : vertexs) {
graph.insertVertex(vertex);
}
graph.insertEdge(0, 1, 1);
graph.insertEdge(0, 2, 1);
graph.insertEdge(1, 3, 1);
graph.insertEdge(1, 4, 1);
graph.insertEdge(3, 7, 1);
graph.insertEdge(4, 7, 1);
graph.insertEdge(2, 5, 1);
graph.insertEdge(2, 6, 1);
graph.insertEdge(5, 6, 1);
graph.showGraph();
System.out.println("深度优先遍历:");
graph.dfs();
System.out.println();
System.out.println("广度优先遍历:");
graph.bfs();
}
public void insertVertex(String vertex) {
vertexList.add(vertex);
}
public void insertEdge(int v1,int v2,int wight) {
edges[v1][v2] = wight;
edges[v2][v1] = wight;
numOfEdges++;
}
public void showGraph() {
for (int[] edge : edges) {
System.out.println(Arrays.toString(edge));
}
}
public void dfs() {
isVisited = new boolean[vertexList.size()];
for (int i = 0; i < vertexList.size(); i++) {
if (!isVisited[i]) {
dfs(isVisited,i);
}
}
}
public void dfs(boolean[] isVisited,int i) {
System.out.print(vertexList.get(i)+" ");
isVisited[i] = true;
int isHas = getFirstNeighbour(i);
while (isHas != -1) {
if (!isVisited[isHas]) {
dfs(isVisited,isHas);
}
isHas = getNextNeighbour(i,isHas);
}
}
public void bfs() {
isVisited = new boolean[vertexList.size()];
for (int i = 0; i < vertexList.size(); i++) {
if (!isVisited[i]) {
bfs(isVisited,i);
}
}
}
public void bfs(boolean[] isVisited,int i) {
Queue<Integer> queue = new LinkedList<>();
System.out.print(vertexList.get(i)+" ");
isVisited[i] = true;
queue.add(i);
while (!queue.isEmpty()) {
int index = queue.poll();
int isHas = getFirstNeighbour(index);
while (isHas != -1) {
if (!isVisited[isHas]) {
System.out.print(vertexList.get(isHas)+" ");
isVisited[isHas] = true;
queue.add(isHas);
}
isHas = getNextNeighbour(index,isHas);
}
}
}
public int getFirstNeighbour(int index) {
for (int i = 0; i < vertexList.size(); i++) {
if (edges[index][i] == 1) {
return i;
}
}
return -1;
}
public int getNextNeighbour(int i,int index) {
for (int j = index+1; j < vertexList.size(); j++) {
if (edges[i][j] == 1) {
return j;
}
}
return -1;
}
}
|