JAVA实现图的邻接表以及DFS

一:定义邻接表结构储存图

package 图的遍历;

//邻接表实现图的建立

//储存边
class EdgeNode {
	int index; // 习惯了用index,其实标准写法是(adjVertex)
	int value; // 权值
	EdgeNode nextArc; // 指向下一条弧
}

// 邻接表节点的类型
class VertexNode {
	String name;
	EdgeNode firstArc = new EdgeNode(); // 指向第一条弧
}

public class Graph {
	VertexNode[] adjList; // 保存邻接表的头节点
	int e; // 图的边数
	int v; // 图的顶点数
	boolean[] visit;

	public Graph(int v, int e) {
		this.v = v;
		this.e = e;
		adjList = new VertexNode[e + 1]; // 学习Java养成的好习惯,动态分配空间,创建顶点表数组
		visit = new boolean[e + 1];  //标记
		for (int i = 0; i < e; i++) {
			visit[i] = false;
		}
	}
}

  二:DFS过程

package 图的遍历;

public class DFSGraph {
	public static void DFS(Graph G, int k) {
		System.out.println(G.adjList[k].name);
		G.visit[k] = true;
		EdgeNode p = new EdgeNode();
		p = G.adjList[k].firstArc;
		while(p!=null){
			if(G.visit[p.index]!=true){
				DFS(G,p.index);
			}
			  
			p=p.nextArc;
		}
	}

}

  三:建立图

package 图的遍历;

import java.util.Scanner;

public class CreateGraph {
	private static Graph G;
	public static Graph getGraph(){
		return G;
	}
	public static void createGraph() {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入顶点数v和边数e:");
		int v = sc.nextInt();
		int e = sc.nextInt();
		G = new Graph(v, e);
		System.out.println("请输入各顶点信息:");
		for (int i = 0; i < G.v; i++) {
			G.adjList[i] = new VertexNode();
			G.adjList[i].name = sc.next();
			G.adjList[i].firstArc = null; // 不可或缺
		}
		System.out.println("请输入各边信息(用空格隔开):");
		for (int i = 0; i < G.e; i++) {
			EdgeNode en1 = new EdgeNode();
			// 保证e1,e2都是合法输入
			String e1 = sc.next();
			String e2 = sc.next();
			int v1 = Index(e1);
			int v2 = Index(e2);
			en1.index = v1; // en1的下标是v1
			en1.nextArc = G.adjList[v2].firstArc;
			G.adjList[v2].firstArc = en1;
			
			EdgeNode en2 = new EdgeNode();
			en2.index = v2; // en2的下标是v2
			en2.nextArc = G.adjList[v1].firstArc;
			G.adjList[v1].firstArc = en2;
		}
	}
	public static void outputGraph() {  //不知道为何空指针异常
		try {
			System.out.println("输出邻接表存储情况:");
			EdgeNode en = new EdgeNode();
			for (int i = 0; i < G.e; i++) {
				System.out.print(G.adjList[i].name);
				en = G.adjList[i].firstArc;
				while (en != null) {
					System.out.print("->" + G.adjList[en.index].name);
					en = en.nextArc;
				}
				System.out.println();
			}
		} catch (NullPointerException e) {

		}

	}
	private static int Index(String e1) {
		for (int i = 0; i < G.v; i++) {
			if (G.adjList[i].name.equals(e1)){
				return i;
			}
		}
		return -1;
	}
}

  四:测试

package 图的遍历;


public class GraphDemo {
	public static void main(String[] args) {
		CreateGraph.createGraph();
		CreateGraph.outputGraph();
		
		System.out.println("DFS图的过程如下:");
		DFSGraph.DFS(CreateGraph.getGraph() , 0);
	}
}
/*
 * 请输入顶点数v和边数e: 4 5 
 * 请输入各顶点信息: a b c d 
 * 请输入各边信息(用空格隔开): 
 * a b
 * a c
 * a d 
 * b c 
 * b d
 */

  五,测试结果

posted @ 2015-11-21 13:47  樱花庄的龙之介大人  阅读(...)  评论(...编辑  收藏