【JAVA】数据结构之深度优先算法

图:

  • 顶点

顶点:

  • 数据项
  • 标志位
class Vertex{
	public char label;
	boolean wasVisited;
	
	public Vertex(char lab) {
		label = lab;
		wasVisited = false;
	}
}

顶点用数组存储,设置最大长度,设置一个变量nVerts记录顶点个数。

边:

  • 用邻接矩阵表示,相连为1,不相连为0
  • 用邻接表表示,此处不讨论

邻接矩阵用二维数组表示,初始化将所有数值都置为0,添加边用两个顶点的索引表示。

	Vertex vertList[];
	final int MAX_VERTS = 20;
	int adjMat[][];
	int nVerts;
	
	public Graph() {
		vertList = new Vertex[MAX_VERTS];
		int nVerts = 0;
		adjMat = new int[MAX_VERTS][MAX_VERTS];
		//将所有元素初始化为0,在添加边的时候只改变特定位置即可
		for(int i=0; i<MAX_VERTS; i++) {
			for(int j=0; j<MAX_VERTS; j++) {
				adjMat[i][j] = 0;
			}
		}
	}

深度优先搜索(dfs):

  1. 修改第一个点的标志位,将第一个点压入栈;

  2. 访问与第一个点相连的其他点,如果有其他点,将其他点入栈,没有就自己出栈;

  3. 访问其他点后,对其他点同样进行1、2操作,直到栈为空。

访问其他点:

  • 判断标志位和邻接矩阵对应位置是否为1。

完整代码:

vpackage graph;

import java.util.*;

class Vertex{
	public char label;
	boolean wasVisited;
	
	public Vertex(char lab) {
		label = lab;
		wasVisited = false;
	}
}


public class Graph {
	/*
	 * 顶点最大个数
	 * 顶点数量统计
	 * 邻接矩阵表示
	 * 顶点数组 
	 */
	Vertex vertList[];
	final int MAX_VERTS = 20;
	int adjMat[][];
	int nVerts;
	
	public Graph() {
		vertList = new Vertex[MAX_VERTS];
		int nVerts = 0;
		adjMat = new int[MAX_VERTS][MAX_VERTS];
		//将所有元素初始化为0,在添加边的时候只改变特定位置即可
		for(int i=0; i<MAX_VERTS; i++) {
			for(int j=0; j<MAX_VERTS; j++) {
				adjMat[i][j] = 0;
			}
		}
	}
	
	public void addVert(char lab) {
		Vertex vert = new Vertex(lab);
		vertList[nVerts++] = vert;
	}
	
	public void addEdge(int start, int end) {
		adjMat[start][end] = 1;
		adjMat[end][start] = 1;
	}
	
	public void display(int v) {
		System.out.println(vertList[v].label);
	}
	
	public int getAdjUnvisitedVertex(int v) {
		for(int j=0; j<nVerts; j++) {
			if(adjMat[v][j] == 1 && vertList[j].wasVisited == false) {
				return j;
			}
		}
		return -1;
	}
	
	public void dfs() {
		Stack<Integer> theStack = new Stack<Integer>();
		
		vertList[0].wasVisited = true;
		display(0);
		theStack.push(0);
		
		while(theStack.isEmpty() != true) {
			int v = getAdjUnvisitedVertex(theStack.peek());
			
			if(v == -1) {
				theStack.pop();
			}
			else
			{
				vertList[v].wasVisited = true;
				theStack.push(v);
				display(v);
			}
		}
		
		for(int j=0; j<nVerts; j++) {
			vertList[j].wasVisited = false;
		}
	}
	
	public static void main(String[] args) {
		Graph gra = new Graph();
		
		gra.addVert('A');
		gra.addVert('B');
		gra.addVert('C');
		gra.addVert('D');
		gra.addVert('E');
		gra.addVert('F');
		gra.addVert('G');
		
		gra.addEdge(0, 1);
		gra.addEdge(0, 4);
		gra.addEdge(0, 6);
		gra.addEdge(1, 3);
		gra.addEdge(3, 5);
		gra.addEdge(4, 2);
		
		gra.dfs();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值