1. 二分图检测
import java.util.LinkedList;
import java.util.Queue;
public class BipartitionDetection {
private Graph G;
private boolean[] visited;
private int[] colors;
private boolean isBipartite = true;
public BipartitionDetection(Graph G){
this.G = G;
visited = new boolean[G.V()];
colors = new int[G.V()];
for(int i = 0; i < G.V(); i ++)
colors[i] = -1;
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
if(!bfs(v)){
isBipartite = false;
break;
}
}
private boolean bfs(int s){
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
visited[s] = true;
colors[s] = 0;
while(!queue.isEmpty()){
int v = queue.remove();
for(int w: G.adj(v))
if(!visited[w]){
queue.add(w);
visited[w] = true;
colors[w] = 1 - colors[v];
}
else if(colors[v] == colors[w])
return false;
}
return true;
}
public boolean isBipartite(){
return isBipartite;
}
}
2. 无权图的最短路径
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class USSSP {
private Graph G;
private boolean[] visited;
private int[] pre;
private int s;
private int[] dis;
public USSSP(Graph g, int s){
this.G = g;
visited = new boolean[g.V()];
pre = new int[g.V()];
dis = new int[g.V()];
for (int i = 0; i < g.V(); i++) {
pre[i] = -1;
dis[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;
dis[s] = 0;
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;
dis[w] = dis[v] + 1;
}
}
}
}
public boolean isConnectedTo(int t){
G.validateVertex(t);
return visited[t];
}
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 int dis(int t){
G.validateVertex(t);
return dis[t];
}
public static void main(String[] args) {
Graph graph = new Graph("g_5.txt");
USSSP usssp = new USSSP(graph, 0);
System.out.println(usssp.isConnectedTo(6));
System.out.println(usssp.path(6));
System.out.println(usssp.dis(6));
}
}
3. BFS与DFS联系