java 广度优先遍历_无向图广度优先遍历及其JAVA实现

2 %文件名: bfst3 % 版本号: 1.0.0

4 % 作者: Isabelle

5 %单位: specter6 % 修改时间: Sat Oct. 8 1:20:01 2017

7 % 创建时间: Sat Oct. 8 1:20:01 2017

8 %--------------------------------------------------------------------------

9 % blog:http://www.cnblogs.com/isabellezhou

10 % Copyright (Dist) 2017Isabelle All rights reserved.11 %============================================

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.Queue;

public class BST{

public static void main(String[] args){

int[][] A=new int[][]{{0,1,1,1,0},{1,0,0,1,0},{1,0,0,0,1},{1,1,0,0,0},{0,0,1,0,0}};

int n=A.length;                                                         //元素个数

ArrayList result=new ArrayList();

Queue thequeue = new LinkedList();                    //LinkedLis实现queue接口

boolean[] marked=new boolean[n];                                        //marked[i]标记是否被遍历过,遍历过为true

for (int i = 0; i < n; i++) {

marked[i] = false;                                                      //初始化标记数组

}

int startNode=3;                                                        //搜索起始结点

thequeue.offer(startNode);                                              //起始结点装入队列

result.add(startNode);                                                  //起始结点装入遍历数组

marked[startNode]=true;                                                 //更新起始结点的访问标志

while(!thequeue.isEmpty()){                                             //队列非空

int v1=(int)thequeue.poll();

for (int k= 0; k

if (A[v1][k]>0&&marked[k]==false&&v1!=k) {

thequeue.offer(k);                                                     //压入队列

marked[k] = true;                                                      //更新访问标志位

result.add(k);                                                         //更新遍历数组

}

}

}

System.out.println(result);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值