代码从网上找的,稍微改了改。
第一遍学习先学到这些吧
public class BFS {
public static class Queue {
public int Depth;
public int Dot;
Queue() {
Depth = -1;
Dot = -1;
}
public void enterQueue(int dot, int dep) {
Dot = dot;
Depth = dep;
System.out.println(Dot + " " + "The Depth is:" + Depth);
}
public int depDate() {
return Depth;
}
public int dotdate() {
return Dot;
}
};
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] Graph = {{0, 1, 0, 0, 1, 0, 0, 0, 0, 0},
{1, 0, 1, 1, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 0, 1, 1, 0, 0},
{0, 0, 1, 0, 0, 1, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 0, 0, 1, 1},
{0, 0, 0, 0, 1, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 1, 0, 0},};
boolean[] vis = new boolean[Graph.length];
Arrays.fill(vis, false);
Queue[] queue = new Queue[Graph.length];
for (int i = 0; i < 10; i++) {
queue[i] = new Queue();
}
BFS1(queue, Graph, vis);
}
/*
可以实现一个起点无法遍历全部节点时的情况
*/
public static void BFS1(Queue[] queue, int[][] Graph, boolean[] vis) {
int base = 0;
int top = 0;
for (int i = 0; i < Graph.length; i++) {
if (vis[i] == false) {
queue[top].enterQueue(i, 1);
top++;
vis[i] = true;
while (top != base) {
int dep = queue[base].depDate() + 1;
int dot = queue[base].dotdate();
for (int j = 0; j < 10; j++) {
if (Graph[dot][j] == 1 && vis[j] == false) {
queue[top].enterQueue(j, dep);
top++;
vis[j] = true;
}
}
base++;
}
}
}
}
}