邻接表广度优先遍历java_java使用邻接表对图进行深度和广度优先遍历

2.[文件]

Traversal_test.java ~ 3KB

下载(37)

package data_struct;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

import java.util.Queue;

import java.util.Scanner;

import java.util.Stack;

public class Traversal_test {

public Vertex dfs[];

public Vertex bfs[];

/*深度优先遍历*/

public void dfs(Graph graph){

int num=graph.ver_List.length;

dfs=new Vertex[num];

Stack dfs_stack=new Stack();

dfs_stack.push(graph.ver_List[0]);

graph.ver_List[0].isVisited=true;//第一个节点访问

int index=0;

dfs[0]=graph.ver_List[0];

while(!dfs_stack.isEmpty()){//栈非空则持续遍历

Vertex v=getAdjVertex(dfs_stack.peek());

if(v==null){

dfs_stack.pop();

}

else{

dfs[++index]=v;

v.isVisited=true;

dfs_stack.push(v);

}

}

}

/*广度优先遍历*/

public void bfs(Graph graph){

int num=graph.ver_List.length;

bfs=new Vertex[num];

ArrayDeque queue=new ArrayDeque();

bfs[0]=graph.ver_List[0];

queue.add(graph.ver_List[0]);

graph.ver_List[0].isVisited=true;

Vertex vv;

int index=0;

while(!queue.isEmpty())

{

Vertex v=queue.remove();

while((vv=getAdjVertex(v))!=null)

{

queue.add(vv);

bfs[++index]=vv;

vv.isVisited=true;

}

}

}

public static Vertex getAdjVertex(Vertex v){

ArrayList alv=v.getAdj();

if(alv!=null){

for(int k=0;k

if(alv.get(k).isVisited==false){

alv.get(k);

return alv.get(k);

}

}

}

return null;

}

public static void main(String[] args) {

System.out.println("Input the number of vertex:");

Scanner scan=new Scanner(System.in);

int node_num=scan.nextInt();

System.out.println("Is this directed graph?");

boolean flag=scan.nextBoolean();

Graph graph=new Graph(node_num,flag);

/*构建图的节点*/

for(int k=0;k

graph.ver_List[k]=new Vertex(k);

}

/*构建图的边*/

System.out.println("Input the each node of each edge:-1 to exit");

int i=0,j=0;

while((i=scan.nextInt())!=-1)

{

j=scan.nextInt();

graph.addEdge(i, j);

}

Traversal_test dt=new Traversal_test();

/*深度优先遍历*/

dt.dfs(graph);

if(dt.dfs.length

System.out.println("The graph is not a connected path!");

}

else{

System.out.println("The depth-first traversal of this graph is:");

for(int k=0;k

System.out.println(dt.dfs[k].toString());

}

}

/*广度优先遍历*/

/*重新构图*/

/*将节点重置为未访问*/

for(int k=0;k

graph.ver_List[k].isVisited=false;

}

dt.bfs(graph);

if(dt.bfs.length

System.out.println("The graph is not a connected path!");

}

else{

System.out.println("The breadth-first traversal of this graph is:");

for(int k=0;k

System.out.println(dt.bfs[k].toString());

}

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值