import java.util.*;
public class BFS {
/**
* @param args
*/
static int[][] edges = {
{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) {
// TODO Auto-generated method stub
bfs();
}
static void bfs()
{
boolean bool[] = new boolean[o];//每个值是否被访问
Queue<Integer> queue = new LinkedList<Integer>();
bool[0]=true;//标记第一个值已被访问
queue.add(0);
System.out.print(res[0]+" ");
while (!queue.isEmpty()) {
int k = queue.poll();//取值并在列队在删除
for (int i = 0; i < o; i++)
{
if (!bool[i]&&edges[k][i]==1) {//判断是否被标记 是否有关联
queue.add(i);//存入列队中
bool[i]=true;//标记当前值已被访问
System.out.print(res[i]+" ");
}
}
}
}
}
原文:https://www.cnblogs.com/shiaguang/p/12340298.html