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);
}
}
有向无环图DAG的广度优先遍历java实现
最新推荐文章于 2024-04-25 11:13:42 发布