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

本文介绍了一种使用邻接表实现图数据结构的方法,并详细展示了深度优先搜索(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]);
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值