[数据结构] - 图的基本实现

本文介绍了一种使用邻接表实现图数据结构的方法,并详细展示了深度优先搜索(DFS)和广度优先搜索(BFS)两种基本的图遍历算法。通过具体的例子,演示了如何在Java中实现这些算法。

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

[数据结构] - 图的基本实现

package p1;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 图 -- (邻接表的实现)
 * @author Guozhu Zhu
 * @date 2019/3/26
 * @version 1.0
 *
 */
public class Demo01 {
	
	public static class Vertex{
		int data;
		public Vertex(int data) {
			this.data = data;
		}
	}
	
	public static class Graph{
		int size = 0;
		public Vertex[] vertexes;
		public LinkedList<Integer>[] adj;
		public Graph(int size) {
			this.size = size;
			vertexes = new Vertex[size];
			adj = new LinkedList[size];
			for (int i = 0; i < size; i++) {
				vertexes[i] = new Vertex(i);
				adj[i] = new LinkedList();
			}
		}
	}
	
	//DFS
	public void DFS(Graph graph, int start, boolean[] visited) {
		System.out.println(graph.vertexes[start].data);
		visited[start] = true;
		for (int index : graph.adj[start]) {
			if (!visited[index]) {
				DFS(graph, index, visited);
			}
		}
	}
	
	//BFS
	public void BFS(Graph graph, int start, boolean[] visited) {
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.offer(start);
		while (!queue.isEmpty()) {
			int front = queue.poll();
			if (!visited[front]) {
				System.out.println(graph.vertexes[front].data);
				visited[front] = true;
				for (int index : graph.adj[front]) {
					queue.offer(index);
				}
			}
		}
	}
	
	/* ========== Test ========== 
	 * [0] -> 1 -> 2
	 * [1] -> 0
	 * [2] -> 1
	 * DFS: 0, 1, 2
	 * BFS: 0, 1, 2
	 * */
	public static void main(String[] args) {
		Demo01 demo = new Demo01();
		Graph graph = new Graph(3);
		graph.adj[0].add(1);
		graph.adj[0].add(2);
		
		graph.adj[1].add(0);
		
		graph.adj[2].add(1);
		
		System.out.println("图的深度遍历算法");
		demo.DFS(graph, 0, new boolean[3]);
		System.out.println("图的广度遍历算法");
		demo.BFS(graph, 0, new boolean[3]);
	}
	
}

 

(Graph)是由顶点的有穷非空集合和顶点之间边的集合组成,通常表示为:G(V,E),其中,G表示一个,V是G中顶点的集合,E是G中边的集合。在中的数据元素,我们称之为顶点(Vertex),顶点集合有穷非空。在中,任意两个顶点之间都可能有关系,顶点之间的逻辑关系用边来表示,边集可以是空的。 按照边的有无方向分为无向和有向。无向由顶点和边组成,有向由顶点和弧构成。弧有弧尾和弧头之分,带箭头一端为弧头。 按照边或弧的多少分稀疏和稠密。如果中的任意两个顶点之间都存在边叫做完全,有向的叫有向完全。若无重复的边或顶点到自身的边则叫简单中顶点之间有邻接点、依附的概念。无向顶点的边数叫做度。有向顶点分为入度和出度。 上的边或弧带有权则称为网。 中顶点间存在路径,两顶点存在路径则说明是连通的,如果路径最终回到起始点则称为环,当中不重复的叫简单路径。若任意两顶点都是连通的,则就是连通,有向则称为强连通中有子,若子极大连通则就是连通分量,有向的则称为强连通分量。 无向中连通且n个顶点n-1条边称为生成树。有向中一顶点入度为0其余顶点入度为1的叫有向树。一个有向由若干棵有向树构成生成森林。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值