图的广度优先遍历(BFS)

使用邻接矩阵进行存储
原图
873621-20180814130703784-1866352410.jpg
调整后
873621-20180814130906052-915939241.jpg

package graph;

import java.util.ArrayList;
import java.util.LinkedList;

public class BFSTraverse {
    private static ArrayList<Integer> list = new ArrayList<Integer>();
    // 邻接矩阵存储;
    public static void main(String[] args) {
        // 初始数据;
        int[] vertexs = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
        int[][] edges = { { 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 1, 0, 1, 0, 0, 0, 1, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 0, 1 },
                { 0, 0, 1, 0, 1, 0, 1, 1, 1 }, { 0, 0, 0, 1, 0, 1, 0, 1, 0 }, { 1, 0, 0, 0, 1, 0, 1, 0, 0 },
                { 0, 1, 0, 1, 0, 1, 0, 1, 0 }, { 0, 0, 0, 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 1, 0, 0, 0, 0, 0 } };
        BFSTraverse(vertexs, edges);
        System.out.println("深度遍历结果:" + list);

    }
    private static void BFSTraverse(int[] vertexs,int[][] edges) {
        boolean[] visited = new boolean[vertexs.length];
        for(int i=0;i<visited.length;i++) {
            visited[i]=false;
        }
        LinkedList<Integer> helper=new LinkedList<Integer>();//辅助队列;
        helper.offerLast(vertexs[0]);//将第一个放入访问队列;
        visited[0]=true;
        BFS(vertexs,edges,visited,helper);
    }
    private static void BFS(int[] vertexs,int[][] edges,boolean[] visited,LinkedList<Integer> helper) {
        while(!helper.isEmpty()) {
            int i = helper.pollFirst();
            
            list.add(i);
            for(int j=0;j<vertexs.length;j++) {
                if(edges[i][j]==1&&!visited[j]) {
                    visited[j]= true; //注意这个放置的位置,应该是将顶点放入到队列的时候进行设置,不能再将顶点从队列取出的时候再设置;
                    helper.offerLast(vertexs[j]);
                }
            }
            
        }
    }
}

转载于:https://www.cnblogs.com/LynnMin/p/9474087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值