编程人 cdmana.com

数据结构-图-广度优先搜索算法(Java语言)

 详细的代码可见github:

https://github.com/AbitGo/myClassWork/tree/master/workspace_ds

如何实现图的广度优先搜索算法

详细代码实现:

package com.company.ch6;

import com.company.ch3.queue.LinkSqeue;

public class GraphFS {
    private static boolean[] visited;

    //广度优先搜索算法的实现
    public static void BFSTraverse(IGraph g) throws Exception {
        visited = new boolean[g.getVexNum()];
        //全部进行初始化,但是java初始化的时候都是false
        for (int v = 0; v < g.getVexNum(); v++) {
            visited[v] = false;
        }
        for (int v = 0; v < g.getVexNum(); v++) {
            //如果当前没被访问
            if (visited[v] == false) {
                BFS(g,v);
            }
        }
        System.out.println();
    }

    public static void BFS(IGraph g,int v) throws Exception {
        //该节点已经被访问过了
        visited[v]=true;
        System.out.print(g.getVex(v).toString()+" ");
        //创建队列
        LinkSqeue linkSqeue = new LinkSqeue();
        //入队
        linkSqeue.offer(v);
        //当队列不为空时
        while (!linkSqeue.isEmpty()){
            //队头元素出队,并赋值给u
            int u = (Integer) linkSqeue.poll();
            //w为第一个邻接点,并且依次往下读取
            for(int w = g.firstAdjVex(u);w>=0;w=g.nextAdjVex(u,w)){
                //当当前邻接点还没有被读取的时候,则进行状态的翻转
                if(!visited[w]){
                    visited[w]=true;
                    System.out.print(g.getVex(w).toString()+" ");
                    linkSqeue.offer(w);
                }
            }
        }
    }
}

测试类:

package com.company.ch6;

public class MGraphTest {
    public static void main(String[] args) throws Exception {
        //无向图
        Object[] param1_1_1= {"UDN",5,5,"ABCDE"};
        String[] param1_1_2 = {"AB1","BC2","AD3","AE4","CE5"};
        MGraph mGraph1 = new MGraph();
        mGraph1.createGraph(param1_1_1,param1_1_2);
        GraphFS.BFSTraverse(mGraph1);
        GraphFS.DFSTraverse(mGraph1);

        //有向图
        Object[] param1_2_1= {"UDN",5,5,"ABCDE"};
        String[] param1_2_2 = {"AB1","BC2","AD3","AE4","CE5"};
        MGraph mGraph2 = new MGraph();
        mGraph2.createGraph(param1_2_1,param1_2_2);
        GraphFS.BFSTraverse(mGraph2);
        GraphFS.DFSTraverse(mGraph2);
    }
}

测试结果:

"C:\Program Files\Java\jdk1.8.0_101\bin\java.exe" 
创建无向网
A B D E C 
A B C E D 
创建无向网
A B D E C 
A B C E D 

 

Scroll to Top