[算法]图(邻接矩阵)的深度遍历

本文介绍了一种使用Java实现图的深度优先遍历(DFS)的方法。通过定义顶点(VertexNode)和弧(ArcNode)节点类,构建了一个包含三个顶点A、B、C的图,并实现了DFS算法来遍历所有可达节点。该实现采用前插法构建邻接表以节省内存。

package com.FeeLang; import java.util.Scanner; class ArcNode{ int adjvex; ArcNode next; } class VertexNode{ char vertex; ArcNode firstedge; } public class Graph { public static void main(String[] args){ int n = 3; int e = 3; char[] vertexs = new char[n]; vertexs[0] = 'A'; vertexs[1] = 'B'; vertexs[2] = 'C'; Graph ALGraph = new Graph(vertexs, n, e); ALGraph.DFS(); } public Graph(char[] vertexs, int node, int edge){ this.node = node; this.edge = edge; adjlist = new VertexNode[this.node]; visited = new boolean[this.node]; for (int i = 0; i < this.node; i++){ adjlist[i] = new VertexNode(); adjlist[i].vertex = vertexs[i]; adjlist[i].firstedge = null; } Scanner sc = new Scanner(System.in); for (int i = 0; i < this.edge; i++){ int v, u; v = sc.nextInt(); u = sc.nextInt(); if (v >= this.node || u >= this.node){ System.out.println("Wrong input"); i--; continue; } //为节省内存采用前插法 ArcNode s = new ArcNode(); s.adjvex = u; s.next = adjlist[v].firstedge; adjlist[v].firstedge = s; } } //output: visited[u] is set to true for all nodes u reachable from v public void explore(int v){ visited[v] = true; System.out.println(v); ArcNode an = adjlist[v].firstedge; while (an != null){ if (!visited[v]){ explore(an.adjvex); } an = an.next; } } public void DFS(){ for (int i = 0; i < this.node; i++){ if (!visited[i]){ explore(i); } } } private VertexNode[] adjlist; private boolean[] visited; private int node; private int edge; }

注意:Line28 and Line31,java数组的空间分配问题。

算法参考:《算法分析与设计》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值