//广度优先搜索树,一定要使用队列,队列的特性很好用 import java.util.*; public class Guangduyouxiansousuosuanfa1 { public static void main(String args[]){ Scanner in=new Scanner(System.in); while(in.hasNext()){ int V=in.nextInt(); int E=in.nextInt(); List<Integer> graph[]=new ArrayList[V+1]; for(int i=0;i<=V;i++) graph[i]=new ArrayList(); for(int i=0;i<E;i++){ int x=in.nextInt(); int y=in.nextInt(); int flag=1; //用邻接表构建无向图 for(int j=0;j<graph[j].size();j++){ if(graph[x].get(j)==y){ flag=0; break; } } if(flag==1){ graph[x].add(y); graph[y].add(x); } } //两个队列一个用于保存结果,一个用于遍历 Queue ans=new LinkedList<>(); Queue tempq=new LinkedList<>(); int visit[]=new int[V+1]; //这里默认从图1节点开始广度优先遍历 ans.offer(1); tempq.offer(1); visit[1]=1; while(tempq.size()>0){ int temp0=(int)tempq.poll(); for(int i=0;i<graph[temp0].size();i++){ int temp1=graph[temp0].get(i); if(visit[temp1]==0){ visit[temp1]=1; tempq.offer(temp1); ans.offer(temp1); } } } //打印结果 int flag2=1; while(ans.size()>0){ if(flag2==1){ System.out.print(ans.poll()); flag2=0; }else{ System.out.print(" "+ans.poll()); } } System.out.println(); } } }
利用队列广度优先搜索图
最新推荐文章于 2023-05-26 20:43:08 发布