图的遍历
1,DFS(深度优先遍历)
访问起始点 v;
若v的第1个邻接点没访问过,深度遍历此邻接点;
若当前邻接点已访问过,再找v的第2个邻接点重新遍历。
结果:
代码实现 图的创建输出看https://blog.csdn.net/qq_37937537/article/details/89056696
基于邻接表实现
/**
* 深度优先遍历
*/
public static void DFS(Vertex vertex, ArrayList<Vertex> visited){
if(visited.size() == vexnum){
return;
}
if(!visited.contains(vertex)){
visited.add(vertex);
System.out.print(vertex.data+" ");
Edge cur = vertex.firstage;
while(cur != null){
DFS(getVertex(cur.adhvex),visited);
cur = cur.next;
}
}
}
public static void main(String[] args) {
createGraph();
outputGraph();
// BFS();
System.out.println();
ArrayList<Vertex> arrayList = new ArrayList<>();
DFS(vertexs[0],arrayList);
}
请输入顶点的个数
5
请输入边的条数
7
请输入各顶点
v1
v2
v3
v4
v5
请按‘头节点 尾节点 回车’的形式依次输入边的信息
v1 v4
v1 v2
v2 v5
v3 v2
v3 v5
v4 v3
v4 v5
v1--v4--v2
v2--v5
v3--v2--v5
v4--v3--v5
v5
v1 v4 v3 v2 v5
2,BFS(广度优先遍历)
在访问了起始点v之后,依次访问 v的邻接点;
然后再依次访问这些顶点中未被访问过的邻接点;
直到所有顶点都被访问过为止。
结果为:1,2,3,4,5,6(从1 开始)
Java代码实现
public static void BFS(){
HashMap<Vertex,Integer> hashMap = new HashMap<>();
LinkedList<Vertex> queue = new LinkedList<>();
queue.add(vertexs[0]);
while(!queue.isEmpty()){
Vertex s = queue.getFirst();
System.out.print(s.data+" ");
hashMap.put(s,1);
queue.removeFirst();
Edge cur = s.firstage;
while (cur != null){
Vertex vertex = getVertex(cur.adhvex);
if(!hashMap.containsKey(vertex)){
queue.add(vertex);
hashMap.put(vertex,1);
}
cur= cur.next;
}
}
}
请输入顶点的个数
5
请输入边的条数
7
请输入各顶点
v1
v2
v3
v4
v5
请按‘头节点 尾节点 回车’的形式依次输入边的信息
v1 v4
v1 v2
v2 v5
v3 v2
v3 v5
v4 v3
v4 v5
v1--v4--v2
v2--v5
v3--v2--v5
v4--v3--v5
v5
v1 v4 v2 v3 v5