import java.util.*;
public class DFS {
// 存储结构
static int[][] es = {
{0,1,0,0,0,0,0,1,0},
{1,0,1,0,1,0,0,0,0},
{0,1,0,1,0,0,0,0,0},
{0,0,1,0,1,1,0,0,0},
{0,1,0,1,0,0,0,0,0},
{0,0,0,1,0,0,1,1,0},
{0,0,0,0,0,1,0,0,0},
{1,0,0,0,0,1,0,0,1},
{0,0,0,0,0,0,0,1,0}
};
static String res[] = { "1","2","3","4","5","6","7","8","9" };
static int o = res.length;
public static void main(String[] args) {
bfs();
}
static void bfs()
{
boolean b[] = new boolean[o];//某个是否值是否被访问
Stack<Integer> l = new Stack<Integer>();
b[0]=true;//找到第一个值 标记已被访问
l.push(0);
System.out.print(res[0]+" ");
aa:while (!l.isEmpty())
{
int k = l.peek();//取出最后一个放进去的值 不删除
for (int i = 0; i <o; i++)
{
if (!b[i]&&es[k][i]==1)
{
b[i]=true;
l.push(i);
System.out.print(res[i]+" ");
continue aa;//结束本次while循环
}
}
l.pop();//找不到没被访问的值 对应到下表 进行弹出最后一个放进去的值
}
}
}
原文:https://www.cnblogs.com/shiaguang/p/12340308.html