图的基本介绍
为什么要有图
我们之前学习的所有数据结构(线性表、树……)不能表示多对多的关系,这时候就需要引入图了!
图的定义及一些概念
简单实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class Graph {
private ArrayList<String> vertexList; private int[][] edges; private int numOfEdges; private boolean[] isVisited;
public Graph(int n) { this.vertexList = new ArrayList<>(); this.edges = new int[n][n]; isVisited = new boolean[n]; }
public void insertVertex(String vertex) { vertexList.add(vertex); }
public void insertEdge(int v1, int v2, int weight) { edges[v1][v2] = weight; edges[v2][v1] = weight; numOfEdges++; }
public int getNumOfVertex() { return vertexList.size(); }
public int getNumOfEdges() { return numOfEdges; }
public String getValueByIndex(int i) { return vertexList.get(i); }
public int getWeight(int v1, int v2) { return edges[v1][v2]; }
public void showGraph() { for (int[] link : edges) { System.out.println(Arrays.toString(link)); } } }
|
图的遍历
深度优先算法(DFS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
public int getFirstNeighbor(int index) { for (int i = 0; i < vertexList.size(); i++) { if (edges[index][i] > 0) { return i; } } return -1; }
public int getNextNeighbor(int v1, int v2) { for (int i = v2 + 1; i < vertexList.size(); i++) { if (edges[v1][i] > 0) { return i; } } return -1; }
private void dfs(boolean[] isVisited, int i) { System.out.print(getValueByIndex(i) + "->"); isVisited[i] = true; int w = getFirstNeighbor(i); while (w != -1) { if (!isVisited[w]) { dfs(isVisited, w); } w = getNextNeighbor(i, w); } }
public void dfs() { for (int i = 0; i < getNumOfVertex(); i++) { if (!isVisited[i]) { dfs(isVisited, i); } } }
|
广度优先算法(BFS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
public void bfs(boolean[] isVisited, int i) { int u; int w;
LinkedList queue = new LinkedList(); System.out.println(getValueByIndex(i) + "->"); isVisited[i] = true; queue.addLast(i);
while (!queue.isEmpty()) { u = (Integer) queue.removeFirst(); w = getFirstNeighbor(u); while (w != -1) { if (!isVisited[w]) { System.out.println(getValueByIndex(w) + "->"); isVisited[w] = true; queue.addLast(w); } w = getNextNeighbor(u, w); } } }
public void bfs() { for (int i = 0; i < getNumOfVertex(); i++) { if (!isVisited[i]) { bfs(isVisited, i); } } }
|