您的位置:首页 > 其它

图的广度优先搜索BFS

2015-01-17 15:43 295 查看
public class BFSDemo {

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 C D E F G H I
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];

LinkedList<Integer> queues = new LinkedList<Integer>();
queues.offer(0);
isVisited[0] = true;
System.out.print(vertices[0] + " ");
while(!queues.isEmpty()) {
int par = queues.poll();
for(int i = 0; i < edges[par].length; i++) {
if(edges[par][i]==1 && !isVisited[i]) {
queues.offer(i);
isVisited[i] = true;
System.out.print(vertices[i] + " ");
}
}
}
System.out.println();
}

}


输出结果:

A B D C E
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: