这里不bb基础了,直接开干
public class Graph {
private char[] vertices;
private int[][] adj;
private int vexnum;
private boolean[] visited;
private Stackz stackz;
public Graph(int n) {
vexnum = n;
vertices = new char[n];
adj = new int[n][n];
visited = new boolean[n];
for (int i = 0; i < vexnum; i++) {
for (int j = 0; j < vexnum; j++) {
adj[i][j] = 0;
}
}
for (int i = 0 ; i < vexnum ; i++){
visited[i] = false;
}
stackz = new Stackz();
}
public void setVertices(char[] vertices){
this.vertices = vertices;
}
public void addEdge(int start , int end) {
adj[start][end] = 1;
adj[end][start] = 1;
}
public void display(int i){
System.out.print(vertices[i] + " ");
}
public int getCanVisied(int v,Graph graph){
for (int i = 0; i < vexnum; i++){
if (adj[v][i] == 1 && graph.visited[i] == false){
return i;
}
}
return -1;
}
public void dfs(Graph graph){
graph.visited[0] = true;
stackz.push(0);
display(stackz.peek());
while (stackz.isEmpty() != -1){
if ( getCanVisied(stackz.peek(),graph)!=-1){
int v = getCanVisied(stackz.peek(),graph);
display(v);
stackz.push(v);
graph.visited[v] =true;
}else {
stackz.pop();
}
}
}
class Stackz {
private int sta[];
private int top ;
public Stackz(){
sta = new int[30];
top = -1;
}
public void push(int s){
sta[++top] = s;
}
public int pop(){
if (top == 0 ){
top--;
return -1;
}else{
return --top;
}
}
public int peek(){
return sta[top];
}
public int isEmpty(){
return top ;
}
}
public static void main(String[] args) {
Graph graph = new Graph(10);
char[] ver = {'A', 'B', 'C', 'D', 'E', 'F'};
graph.setVertices(ver);
graph.addEdge(0, 1);
graph.addEdge(0, 5);
graph.addEdge(1, 0);
graph.addEdge(1, 2);
graph.addEdge(2, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 2);
graph.addEdge(3, 4);
graph.addEdge(4, 3);
graph.addEdge(4, 5);
graph.addEdge(5, 0);
graph.addEdge(5, 4);
System.out.print("深度优先遍历:");
graph.dfs(graph);
}
}