import java.util.Stack;

public class DFSDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
char[] vertices = {'A', 'B', 'C', 'D', 'E'};
int[][] edges = {
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 0},
{0, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}
};
/*第二组测试数据->输出结果->A B F H C D G I E
* char[] vertices = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
int[][] edges = {
{0, 1, 1, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0}
};*/
boolean[] isVisited = new boolean[vertices.length];
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
isVisited[0] = true;
System.out.print(vertices[0] + " ");
while(!stack.isEmpty()) {
int v = getAdjUnvisitedVertex(stack.peek(), edges, isVisited);
if(v == -1) {
stack.pop();
} else {
stack.push(v);
isVisited[v] = true;
System.out.print(vertices[v] + " ");
}
}
System.out.println();
}

public static int getAdjUnvisitedVertex(int cur, int[][] edges, boolean[] isVisited) {
// TODO Auto-generated method stub
for(int i = 0; i < edges[cur].length; i++) {
if(edges[cur][i]==1 && !isVisited[i]) {
return i;
}
}
return -1;
}

}

输出结果:

A B C D E