图,深度,广度优先遍历(一)
What is graph? 图可以这样定义。 G=(V,E)
V:图中所有顶点Vertex的集合Vertices;
E:图中边的集合;
例子:
边肯定连着两个顶点,那么一条边可以如此表示{v1,v2}。
可以用二维数组表示int[][].或者定义一个Edge类
public class Edge { int u; //starting vertex; int v; //ending vertex; public Edge(int u,int v) { this.u = u; this.v = v; } }
边的集合就是java.util.ArrayList<Edge> edges = new java.util.ArrayList<Edge>();
要对图进行处理,一般需要建立邻接矩阵AdjacencyMatrix;
用java的集合框架可以很方便地建立邻接矩阵
neighbours = new ArrayList<List<Integer>>();
建立邻接矩阵的方法:
private void createAdjacencyLists(int[][] edges, int numberOfVertices) { neighbours = new ArrayList<List<Integer>>(); for (int i = 0; i < numberOfVertices; i++) { neighbours.add(new ArrayList<Integer>()); } for (int i = 0; i < edges.length; i++) { int u = edges[i][0]; //starting vertex; int v = edges[i][1]; //ending vertex; neighbours.get(u).add(v); } } private void createAdjcacencyLists(List<Edge> edges, int numberOfVertices) { neighbours = new ArrayList<List<Integer>>(); for (int i = 0; i < numberOfVertices; i++) { neighbours.add(new ArrayList<Integer>()); } for (Edge edge:edges) { neighbours.get(edge.u).add(edge.v); } }
对图进行遍历所得的子图其实为一棵生成树;
故应该写一个数据结构Tree用来存放遍历所得生成树;
基本结构:
public class Tree { private int root; private int[] parent; private List<Integer> searchOrders; public Tree(int root, int[] parent, List<Integer> searchOrders) { this.root = root; this.parent = parent; this.searchOrders = searchOrders; } }
后面的内容将要围绕这几个基本概念进行开展。