图的广度优先搜索BFS

来源:互联网 发布:分众传媒江南春 知乎 编辑:程序博客网 时间:2024/06/05 20:17
public class BFSDemo {public static void main(String[] args) {// TODO Auto-generated method stubchar[] 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

0 0