有向无环图DAG的广度优先遍历java实现

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
//有向无环图DAG广度优先遍历
public class DAG_BFS {
	public static void main(String[] args) {
		
		String[] input = {"A-> B","A->C.D","C->E","E->F","D->G","G->E"};
		String input2 ="A";
		//构建路径列表
		int[][] A=new int[26][26];
		int n=0;
		for (int i =0;i<input.length;i++) {
			String nowdata=input[i];
			nowdata=nowdata.replace(" ", "");
			String[] newdata= nowdata.split("->");
			
			if(newdata[1].length()>1) {
				//注意.要加转义
				String[] lastdata = newdata[1].split("\\.");
				for(int j =0;j<lastdata.length;j++) {
					//字符串转换为字符
					char[] chardata = newdata[0].toCharArray();
					char[] chardata2 = lastdata[j].toCharArray();
					//转换大写字母到0~25
					int mnum = (int)chardata[0]-65;
					int mnum2 = (int)chardata2[0]-65;
					n=n<mnum?mnum:n;
					n=n<mnum2?mnum2:n;
					A[mnum][mnum2]=1;
				}
			}
			else {
				char[] chardata = newdata[0].toCharArray();
				char[] chardata2 = newdata[1].toCharArray();
				int mnum = (int)chardata[0]-65;
				int mnum2 = (int)chardata2[0]-65;
				n=n<mnum?mnum:n;
				n=n<mnum2?mnum2:n;
				A[mnum][mnum2]=1;
			}
		}
		n++;//元素个数
		                                                       
		//搜索起始结点
		char[] chardata=input2.toCharArray();
		int startNode= (int)chardata[0]-65;
		
		String result ="";
		Queue<Integer> thequeue = new LinkedList<Integer>();                    //LinkedLis实现queue接口
		boolean[] marked=new boolean[n];                                        //marked[i]标记是否被遍历过,遍历过为true
		for (int i = 0; i < n; i++) {
			marked[i] = false;                                                      //初始化标记数组
		}
		thequeue.offer(startNode);                                              //起始结点装入队列
		result+=(char)(startNode+65);                                                  //起始结点装入遍历数组
		marked[startNode]=true;                                                 //更新起始结点的访问标志
	
		while(!thequeue.isEmpty()){                                             //队列非空
			int v1=(int)thequeue.poll();
			for (int k= 0; k<n; k++) { 
				if (A[v1][k]>0&&marked[k]==false&&v1!=k) {
					thequeue.offer(k);                                                     //压入队列
					marked[k] = true;                                                      //更新访问标志位
					result+=","+(char)(k+65);                                                           //更新遍历数组
				}
			}
		}
		System.out.println(result);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值