每天学一点算法-BFS

来源:互联网 发布:丸子网络传世论坛 编辑:程序博客网 时间:2024/05/27 01:19

广度优先搜索


定义


广度优先搜索算法(Breadth-First-Search),是一种图形搜索算法。简单的说,BFS 是从根节点开始,沿着树(图)的宽度遍历树(图)的节点。如果所有节点均被访问,则算法中止。BFS 同样属于盲目搜索。一般用队列数据结构来辅助实现 BFS 算法。


算法步骤


 1.首先将根节点放入队列中。

2.  从队列中取出第一个节点,并检验它是否为目标。

     如果找到目标,则结束搜寻并回传结果。

    否则将它所有尚未检验过的直接子节点加入队列中。

3.  若队列为空,表示整张图都检查过了——亦即图中没有欲搜寻的目标。结束搜寻并回传“找不到目标”。

4.  重复步骤2。



问题


广度遍历下图,无向图。



时间复杂度


当用二维数组表示邻接矩阵作图的存储结构时,查找每个顶点的邻接点所需时间为

O(n^2),

其中n为顶点数.

而当以邻接表作图的存储结构时,找邻接点所需时间为O(e),其中e为无向图中边的数或有向图中弧的数。

由此,当以邻接表作存储结构时,深度优先搜索遍历图的时间复杂度为

O(n+e).


代码


public class BFS {static Map<Integer, String> points = new HashMap<Integer, String>();static {points.put(0, "A");points.put(1, "B");points.put(2, "C");points.put(3, "D");points.put(4, "E");points.put(5, "F");points.put(6, "G");points.put(7, "H");points.put(8, "I");}LinkedBlockingQueue<Integer> queue;boolean[] hasVisits;int[][] arcs;public void search(int[][] args, int begin) throws InterruptedException {if (args == null || args.length == 0 || args.length != args[0].length) {System.out.println("邻接矩阵有问题,退出");return;}arcs = args;hasVisits = new boolean[args.length];for (int i = 0; i < args.length; i++) {hasVisits[i] = false;}// 初始化辅助队列queue = new LinkedBlockingQueue<Integer>();for (int i = 0; i < arcs.length; i++) {if (!hasVisits[i]) {hasVisits[i] = true;System.out.println("经过顶点 : " + points.get(i));queue.put(i);while (!queue.isEmpty()) {int index = queue.poll();for (int j = 0; j < arcs.length; j++) {if (arcs[index][j] == 1 && !hasVisits[j]) {hasVisits[j] = true;System.out.println("经过顶点 : " + points.get(j));queue.put(j);}}}}}}public static void main(String[] args) {BFS bfs = new BFS();// 无向图,无权值,用邻接矩阵表示如下int[][] datas = { { 0, 1, 0, 0, 0, 1, 0, 0, 0 },// A点矩阵{ 1, 0, 1, 0, 0, 0, 1, 0, 1 },// B点矩阵{ 0, 1, 0, 1, 0, 0, 0, 0, 1 },// C点矩阵{ 0, 0, 1, 0, 1, 0, 1, 1, 1 },// D点矩阵{ 0, 0, 0, 1, 0, 1, 0, 1, 0 },// E点矩阵{ 1, 0, 0, 0, 1, 0, 1, 0, 0 },// F点矩阵{ 0, 1, 0, 1, 0, 1, 0, 1, 0 },// G点矩阵{ 0, 0, 0, 1, 1, 0, 1, 0, 0 },// H点矩阵{ 0, 1, 1, 1, 0, 0, 0, 0, 0 },// I点矩阵};int begin = 0;try {bfs.search(datas, begin);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

输出


经过顶点 : A经过顶点 : B经过顶点 : F经过顶点 : C经过顶点 : G经过顶点 : I经过顶点 : E经过顶点 : D经过顶点 : H



0 0
原创粉丝点击