图的广度优先搜索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
相关文章推荐
- 广度优先搜索BFS 之图的构造及遍历
- 广度优先搜索BFS-C实现、思路、解析和总结
- BFS广度优先搜索——入门
- HDU/HDOJ 2102 A计划 广度优先搜索BFS
- 数据结构搜索算法之广度优先搜索 (BFS)
- sdut 3468 广度优先搜索练习之神奇的电梯(BFS)
- 数据结构之 图论---基于邻接矩阵的广度优先搜索遍历(输出bfs遍历序列)
- 22.基于 邻接表 表示的 深度优先搜索dfs 和 广度优先搜索bfs
- 图的深度优先搜索DFS和广度优先搜索BFS
- [模板]广度优先搜索BFS
- 广度/宽度优先搜索(BFS)
- 【算法入门】广度/宽度优先搜索(BFS)
- 广度/宽度优先搜索(BFS)
- 广度优先搜索BFS——图邻接表表示
- bfs广度优先搜索对于图的遍历顺序
- bfs广度优先搜索经典模板题目
- 广度优先搜索-BFS
- javascript实现的图数据结构的广度优先 搜索(Breadth-First Search,BFS)和深度优先搜索(Depth-First Search,DFS)
- 广度/宽度优先搜索(BFS)
- 数据结构和算法总结(一):广度优先搜索BFS和深度优先搜索DFS