图的邻接表存储及遍历(JAVA)

本文介绍了一种使用邻接表表示图的方法,并通过Java实现了广度优先搜索(BFS)与深度优先搜索(DFS)。该方法为每个顶点创建了一个单链表来存储其相邻节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为图的每个顶点所发出的边建立一个单链表,用一顶点数组存储每个单链表的头指针。
[img]http://dl.iteye.com/upload/attachment/0074/7828/27d47812-8e3c-3592-b73c-fa1372131fcb.gif[/img]

[img]http://dl.iteye.com/upload/attachment/0074/7830/c9c0ca3b-df72-34f9-b70e-ea874c5f0676.gif[/img]

import java.util.*;
class VNode{
int from;//边的起点
Edge first;//以from为起点的第一条边
public VNode(int from){
this.from=from;
first=null;
}
}

class Edge{
int to;//边的终点
Edge next;//具有同一起点的下一条边
public Edge(int to){
this.to=to;
next=null;
}
}

public class Graph{
int k;//图的顶点数
VNode[] V;//顶点数组
boolean[] visted;//记录某个顶点是否遍历过

public Graph(int k,VNode[] v){
this.k=k;
this.V=v;
visted = new boolean[k];
}

//从v0顶点出发广度优先遍历图

private void BFS(int v0){
Queue<Integer> que=new LinkedList<Integer>();
que.add(v0);
while(!que.isEmpty()){
v0=que.poll();
if(!visted[v0]){
System.out.print(v0+" ");
visted[v0]=true;
}
Edge e=V[v0].first;
while(e!=null){
if(!visted[e.to]) que.add(e.to);
e=e.next;
}

}
}


//邻接表深度优先搜索图

private void DFS(int v0){
visted[v0]=true;
//访问顶点v0
System.out.print(v0+" ");

Edge p=V[v0].first;
while(p!=null){
if(!visted[p.to]){
DFS(p.to);
}
p=p.next;
}
}

public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int k=sc.nextInt();//图的顶点数
int m=sc.nextInt();//图的边数

VNode[] V=new VNode[k];
for(int i=0;i<k;i++)
V[i]=new VNode(i);
Edge e=null;Edge e1=null;
int u=0;int v=0;
for(int i=0;i<m;i++){
u=sc.nextInt();//起点
v=sc.nextInt();//终点
e=new Edge(v);
e.next=V[u].first;//插入到链表开头
V[u].first=e;

//对于无向图作对称处理
e1=new Edge(u);
e1.next=V[v].first;
V[v].first=e1;
}

Graph gra=new Graph(k,V);
// gra.BFS(0);
gra.DFS(0);
}
}



[img]http://dl.iteye.com/upload/attachment/0074/7826/761b65d5-8146-38e4-8ec2-e977ca9e0de0.gif[/img]


程序运行:
C:\java>java Graph
6
10
0 1
0 2
0 3
1 2
1 4
2 4
2 5
2 3
3 5
4 5
0 3 2 1 5 4(广搜)


C:\java>java Graph
6
10
0 1
0 2
0 3
1 2
1 4
2 4
2 5
2 3
3 5
4 5
0 3 5 4 2 1(深搜)
下载源码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值