1. 树的广度优先遍历与图的广度优先遍历对比
时间复杂度:O(V+E)
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GraphBFS {
private Graph G;
private boolean[] visited; //是否进入过队列
private ArrayList<Integer> order = new ArrayList<>();
GraphBFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
for (int v = 0; v < G.V(); v++) {
if(!visited[v])
bfs(v);
}
}
private void bfs(int s){
Queue<Integer> queue = new LinkedList<>();
visited[s] = true;
queue.add(s);
while(!queue.isEmpty()){
int v = queue.remove();
order.add(v);
for(int w:G.adj(v)){
if(!visited[w]){
queue.add(w);
visited[w] = true;
}
}
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args) {
Graph graph = new Graph("g_5.txt");
GraphBFS graphBFS = new GraphBFS(graph);
System.out.println(graphBFS.order());
}
}
2. 联通分量
参考图的深度优先遍历的应用1,只需将对应的dfs改为bfs即可。
3. 路径问题
- 单源路径
import java.util.*;
public class SingleSourcePath {
private Graph G;
private boolean[] visited;
private int[] pre; //保存到达某个点的上个节点的编号
private int s; //source:从哪个源头开始
public SingleSourcePath(Graph g, int s){
this.G = g;
visited = new boolean[g.V()];
pre = new int[g.V()];
for (int i = 0; i < g.V(); i++) {
pre[i] = -1;
}
this.s = s;
bfs(s);
}
private void bfs(int s){
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
visited[s] = true;
pre[s] = s;
while(!queue.isEmpty()){
int v = queue.remove();
for(int w:G.adj(v)){
if(!visited[w]){
queue.add(w);
visited[w] = true;
pre[w] = v;
}
}
}
}
public boolean isConnectedTo(int t){
G.validateVertex(t);
return visited[t]; //return pre[t] != -1;
}
public Iterable<Integer> path(int t){
ArrayList<Integer> res = new ArrayList<>();
if(!isConnectedTo(t)) return res;
int cur = t;
while(cur != s){
res.add(cur);
cur = pre[cur];
}
res.add(s);
Collections.reverse(res);
return res;
}
public static void main(String[] args) {
Graph graph = new Graph("g_5.txt");
SingleSourcePath singleSourcePath = new SingleSourcePath(graph, 0);
System.out.println(singleSourcePath.isConnectedTo(6));
System.out.println(singleSourcePath.path(6));
}
}
4. 环检测
无向图有环:
- 当前点的邻接节点已经被访问过
- 被访问过的邻接节点不是当前节点的上个访问
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class CycleDetection {
private Graph G;
private boolean[] visited;
private int[] pre; //保存到达某个点的上个节点的编号
private boolean hasCycle = false;
public CycleDetection(Graph G){
this.G = G;
visited = new boolean[G.V()];
pre = new int[G.V()];
for(int i = 0; i < G.V(); i ++)
pre[i] = -1;
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
if(bfs(v)){
hasCycle = true;
break;
}
}
// 从顶点 v 开始,判断图中是否有环
private boolean bfs(int s){
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
visited[s] = true;
pre[s] = s;
while(!queue.isEmpty()){
int v = queue.remove();
for(int w: G.adj(v))
if(!visited[w]){
queue.add(w);
visited[w] = true;
pre[w] = v;
}
else if(pre[v] != w)
return true;
}
return false;
}
public boolean hasCycle(){
return hasCycle;
}
}
- 注:本系列参考玩转算法系列–图论精讲