图的代码实现:
package com.model.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/7/17 15:16 * 演示图的实现,图的快速入门 */ public class GraphDemo01 { public static void main(String[] args) { Graph graph = new Graph(5); graph.insertVertex("A"); graph.insertVertex("B"); graph.insertVertex("C"); graph.insertVertex("D"); graph.insertVertex("E"); graph.addEdges(0, 1, 1); graph.addEdges(0, 2, 1); graph.addEdges(1, 2, 1); graph.addEdges(1, 3, 1); graph.addEdges(1, 4, 1); graph.showGraph(); } } class Graph{ private List<String> vertexList=null;//保存节点的list private int[][] edges=null;//保存边的矩阵 private int numEdges=0;//边的数目 public Graph(int n) { vertexList=new ArrayList<>(n); edges=new int[n][n]; numEdges=0; } // 保存节点的值,第一个节点的名字 public void insertVertex(String vertex){ vertexList.add(vertex); } // 添加边 public void addEdges(int v1,int v2,int weight){ edges[v1][v2]=weight; edges[v2][v1]=weight; numEdges++; } public int getNumOfVertex(){ return vertexList.size(); } public int getNumEdges(){ return numEdges; } // 返回节点的值,名字 public String getVertex(int index){ return vertexList.get(index); } public int getWeight(int v1,int v2){ return edges[v1][v2]; } public void showGraph(){ for (int[] arr:edges){ System.out.println(Arrays.toString(arr)); } } }
图的遍历-深度优先(DFS):
public void dfs(){ for (int i = 0; i < getNumEdges(); i++) { if (!isVisited[i]){ dfs(isVisited, i); } } } // 深度优先算法 private void dfs(boolean[] isVisited, int index) { isVisited[index] = true; System.out.print(vertexList.get(index)+"->"); int neighbor = getFirstNeighbor(index); while (neighbor != -1) { if (!isVisited[neighbor]) { dfs(isVisited, neighbor); } neighbor = getNextNeighbor(index, neighbor); } }
图的遍历-广度优先算法(BFS):
// 广度优先遍历算法 public void bfs(){ isVisited = new boolean[getNumOfVertex()]; for (int i = 0; i < isVisited.length; i++) { if (!isVisited[i]){ bfs(isVisited,i); } } } // 广度优先遍历算法 public void bfs(boolean[] isVisited, int index){ int u; //队列的头节点的小标 int w;//邻接节点 LinkedList queue=new LinkedList();//记录节点的访问顺序 System.out.print(getVertex(index)+"->"); isVisited[index]=true; queue.addLast(index); while(!queue.isEmpty()){ u= (int) queue.removeFirst(); w=getFirstNeighbor(u); while (w!=-1){ if (!isVisited[w]){ System.out.print(getVertex(w)+"->"); isVisited[w]=true; queue.addLast(w); }else { w=getNextNeighbor(u, w); } } } }
Graph graph1 = new Graph(8); graph1.insertVertex("1"); graph1.insertVertex("2"); graph1.insertVertex("3"); graph1.insertVertex("4"); graph1.insertVertex("5"); graph1.insertVertex("6"); graph1.insertVertex("7"); graph1.insertVertex("8"); graph1.addEdges(0, 1, 1); graph1.addEdges(0, 2, 1); graph1.addEdges(1, 3, 1); graph1.addEdges(1, 4, 1); graph1.addEdges(3, 7, 1); graph1.addEdges(4, 7, 1); graph1.addEdges(2, 5, 1); graph1.addEdges(2, 6, 1); graph1.addEdges(5, 6, 1); graph1.showGraph(); System.out.println("深度优先算法"); graph1.dfs(); System.out.println(); System.out.println("广度优先算法"); graph1.bfs();