广度优先遍历
图的广度优先遍历和树的广度优先遍历本质是一样的。 由于图大多有环,我们需要在进行图的广度优先遍历时,我么需要记住那些顶点已经被遍历过。 树的广度优先遍历又叫树的层序遍历,通常使用一个队列 来实现。
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<>();
public 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<>();
queue.offer(s) ;
visited[s] = true;
while (!queue.isEmpty()){
int v = queue.poll();
order.add(v) ;
for(int w : g.adj(v)){
if(!visited[w]){
queue.offer(w) ;
visited[w] = true;
}
}
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
GraphBFS graphBFS =new GraphBFS(g);
System.out.println("BFS order:"+ graphBFS.order());
}
}
时间复杂度 : O(V +E) 所有的顶点都入了一次队伍 V , 每个边都遍历了一次for (int w : g.adj(v)
E 所有深度优先遍历能解决的问题,广度优先遍历都可以解决。
BFS求解单源路径问题
对起点s进行一次广度优先遍历,同样,需要像深度优先遍历一样,我们需要一个数组pre记录在遍历过程中,每一个顶点的前驱顶点(从哪一个顶点到达当前这个顶点)。 pre[ 0…v-1] = -1初始时,都为-1 表示还没有遍历过,(没有遍历过,自然就不存在前驱) 同样,这个数组可以取代visited数组 为了语义清晰,我们还是使用visited作为访问标记数组。 下面只需要对BFS方法进行小小从改动,就可以求解单源路径问题。
private void bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s) ;
visited[s] = true;
pre[s] = s; // 第一处改动
while (!queue.isEmpty()){
int v = queue.poll();
for(int w : g.adj(v)){ // v的所有邻接点都是w
if(!visited[w]){
queue.offer(w) ;
visited[w] = true;
pre[w] = v ; // 第二处改动
}
}
}
}
下面是完整的代码:
import java.util.*;
public class SingleSourcePathBFS {
private Graph g;
private boolean[] visited;
private int[] pre;
private int s;
public SingleSourcePathBFS(Graph g, int s) {
this.g = g;
this.s = s;
visited = new boolean[g.V()];
pre = new int[g.V()];
for (int i = 0; i < g.V(); i++) {
pre[i] = i;
}
bfs(s); // s到其他连通分量是不可达的
}
// 广度优先遍历寻路
private void bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
pre[s] = s; // 改动1 添加起点s的上一个顶点就是自己
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]) {
queue.offer(w);
visited[w] = true;
pre[w] = v; //改动2 v的所有邻接点w的前驱都是v
}
}
}
}
//判断顶点s到顶点t是否可达 如果被遍历到了肯定是可达的
public boolean isConnectionTo(int t) {
g.validateVertax(t);
return visited[t];
}
// 返回起点s到目标点t的路径
public Iterable<Integer> path(int t) {
ArrayList<Integer> res = new ArrayList<>();
if (!isConnectionTo(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 g = new Graph("g.txt");
SingleSourcePathBFS singleSourcePathBFS =new SingleSourcePathBFS(g, 0) ;
System.out.println("0-->6:"+singleSourcePathBFS.path(6));
}
}
其他BFS的应用, 比如求解连通分量的个数, 具体的连通分量 、环检测、二分图检测 下面一一给出参考代码
BFS求解联通分量的个数
关于读取图的文件,建立图,可以参考我的往期文章,图的基本表示
import java.util.LinkedList;
import java.util.Queue;
// 使用广度优先遍历求解连通分量的个数
public class CcBfs {
private Graph g;
private boolean[] visited;
private int ccount = 0; // 统计连通分量的个数
public CcBfs(Graph g) {
this.g = g;
visited = new boolean[g.V()];
for (int v = 0; v < g.V(); v++) {
if (!visited[v]) {
bfs(v);
ccount++;
}
}
}
// 广度优先遍历,对图的一个连通分量进行遍历标记
private void bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
visited[s] = true;
queue.offer(s);
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]) {
visited[w] = true;
queue.offer(w);
}
}
}
}
// 返回连通分量的个数
public int getCcount() {
return ccount;
}
public static void main(String[] args) {
Graph g = new Graph("g.txt");
Graph g2 =new Graph( "g2.txt") ;
CcBfs ccBfs = new CcBfs(g);
CcBfs ccBfs2 =new CcBfs(g2) ;
System.out.println(ccBfs.getCcount());
System.out.println(ccBfs2.getCcount());
}
}
具体的每一个连通分量都包含哪些顶点
就像在广度优先遍历中 求解每一个顶点属于哪个连通分量 的方法一样,我们同样 我们可以新开一个int 类型的数组,下标代表顶点编号,值保存 该顶点属于哪一个连通分量。或者直接把visited数组改造成 int 类型 初始全部为-1,承担双重语义。 这里我选择新开一个数组 , 这样使得代码更加容易阅读。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class CcBfsAdv {
private Graph g;
private boolean[] visited;
private int[] comp;
private int ccount;
public CcBfsAdv(Graph g) {
this.g = g;
ccount = 0;
visited = new boolean[g.V()];
comp = new int[g.V()];
for (int v = 0; v < g.V(); v++)
comp[v] = -1;
for (int v = 0; v < g.V(); v++) {
if (!visited[v]) {
bfs(v);
ccount++;
}
}
}
// 我们在标记顶点属于哪个连通分量有两种方式,一种是在顶点出队的时候标记 一种是在入队的时候进行标记
// 不管使用哪种方式,唯一要保证的是,在一次bfs的过程中,所有遍历的顶点都要标记上属于哪个连通分量
// 一次bfs过程中遍历到的顶点 属于同一个连通分量
private void bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
while (!queue.isEmpty()) {
int v = queue.poll();
comp[v] = ccount; // 出队的时候进行标记
for (int w : g.adj(v)) {
if (!visited[w]) {
queue.offer(w);
visited[w] = true;
}
}
}
}
// 返回每一个连通分量的顶点集合 返回类型是一个ArrayList 数组
public ArrayList<Integer>[] components() {
ArrayList<Integer>[] res = new ArrayList[ccount];
for (int i = 0; i < ccount; i++)
res[i] = new ArrayList<>();
for (int v = 0; v < comp.length; v++) {
res[comp[v]].add(v);
}
return res;
}
//判断两个顶点是否在同一个连通分量中
public boolean isconnection(int s, int t) {
g.validateVertax(s);
g.validateVertax(t);
return comp[s] == comp[t];
}
// 打印整个连通分量标记数组
public void showCount(){
System.out.print("components: ");
for(int e : comp){
System.out.print(e + " ");
}
System.out.println();
}
// 测试
public static void main(String [ ] args){
Graph g = new Graph("g.txt");
CcBfsAdv ccBfsAdv =new CcBfsAdv(g) ;
ArrayList<Integer> [] components = ccBfsAdv.components();
for(int ccid = 0 ;ccid< components.length ;ccid++){
System.out.print("ccid " + ccid+" : ");
for(int v : components[ccid]){
System.out.print(v+" ");
}
System.out.println();
}
}
}
环检测
我们先考虑一下,图中没有环是什么情况,如果图中没有环,对于每一个连通分量来说,这个连通分量一定是一棵树。如果是多个连通分量,组成的就是一片森林。 鉴于我们使用广度优先遍历,一层一层向外扩展扫描, 那么,如果当前我们在 顶点v 此时要向外遍历一层,也就是遍历它所有的邻接顶点w , 如果此时发现 邻接点中有一个顶点已经别访问过了, 并且这个顶点还不是顶点v的前驱, 那么 我们就说现在找到了一个环。
想像一下,我们面对的是一个一个的由道路连接起来的城市。当我们站在城市A 向外访问它的相邻的城市B ,此时发现城市B已经被访问了。 试想,我们是一层一层向外访问, 此时却发现,A的下一层中的某一城市B已经被访问了, 如果这个城市B不是A的前驱,那么一定有另一条从起点到B的路存在。并且这个起点到B的路径 比 起点先到A再由A到B要更短。 那么我们知道了,从起点到A A到B 在由B通过更短的路径回到起点,这样就构成了一个环。
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 v = 0; v < pre.length; v++) // 初始时,每一个顶点的前驱都是自己
pre[v] = v;
for (int v = 0; v < g.V(); v++) {
if (!visited[v]) {
if (bfs(v)) {
hasCycle = true; // 找到一个环之后,就停下来
break;
}
}
}
}
private boolean bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
pre[s] = s;
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]) {
queue.offer(w);
visited[w] = true;
pre[w] = v;
// 只需要在这里进行改动 如果w这个顶点已经被访问过,并且不是v的前驱顶点 那么就出现了环
} else if (pre[v] != w)
return true;
}
}
return false;
}
public boolean isHasCycle(){
return hasCycle;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
Graph g2 = new Graph("g2.txt");
CycleDetection cycleDetection = new CycleDetection(g) ;
CycleDetection cycleDetection2 = new CycleDetection(g2);
System.out.println(cycleDetection.isHasCycle());
System.out.println(cycleDetection2.isHasCycle());
}
}
二分图的检测
使用广度优先遍历 也可以对二分图进行检测,其实也比较简单。 对于二分图来说,每一个顶点和它相邻的顶点类别都不同, 或者颜色都不同(如果用染色来形容的话)。那么我们就知道了, 我们的广度优先遍历是从起点 s 一层一层向外扩展的。s和它相邻的一层颜色不同, s相邻的一层 和它的下一层颜色也不相同。 总的来说,就是,在广度优先遍历一圈一圈向外扩散时,相邻的两层颜色是不同的。
那么我们的思路就是,顶点w的邻接点 如果还没有染色的话,我们就把它染成 与顶点w不同的颜色,如果已经染色的话,我们就要看看,这个颜色和顶点w是不是相同, 如果相同,那么 这不是一个二分图。 基于这样的逻辑来编写我们的代码:
import java.util.LinkedList;
import java.util.Queue;
public class BipartitionDetection {
private Graph g;
private boolean[] visited;
private int[] colors;
private int color = 0;
private boolean isBipartition;
public BipartitionDetection(Graph g) {
this.g = g;
isBipartition = true; // 初始赋值为true
visited = new boolean[g.V()];
colors = new int[g.V()];
for (int v = 0; v < g.V(); v++)
colors[v] = -1; // 初始赋值都为-1 表示当前顶点还没有进行染色
for (int v = 0; v < g.V(); v++) {
if (!visited[v]) {
if (!bfs(v)) { // 如果检测出不是二分图 提前终止循环
isBipartition = false;
break;
}
}
}
}
private boolean bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
colors[s] = color;
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]) {
queue.offer(w);
visited[w] = true;
colors[w] = 1 - colors[v]; //染色
} else if (colors[w] == colors[v])// 判断
return false;
}
}
return true;
}
public boolean isBipartition(){
return isBipartition;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
Graph g2 = new Graph("g2.txt");
BipartitionDetection bipartitionDetection =new BipartitionDetection(g);
BipartitionDetection bipartitionDetection2 =new BipartitionDetection(g2) ;
System.out.println(bipartitionDetection.isBipartition());
System.out.println(bipartitionDetection2.isBipartition());
}
}
BFS的重要性质
广度优先遍历得到的是最短路径。一层一层向外遍历。 后遍历的顶点一定是基于先遍历的顶点的。
首先遍历1步就能到达的顶点,然后在遍历2步才能到达的顶点,然后遍历3步才能到达的顶点 依次类推。这个遍历是顺次的。当遍历到这个点时,一定是最早到达的时刻。
我们如何快速获得每一个顶点距离起始点的距离呢?我们现在讲的是无权图,每一个顶点到起点的距离是它的前驱顶点到起点距离+1
import java.util.*;
public class UnweightSingleSourcePathBFS {
private Graph g;
private int s;
private boolean[] visited;
private int[] pre;
private int[] dis; // 各个点到起点的距离
public UnweightSingleSourcePathBFS(Graph g, int s) {
this.g = g;
this.s = s;
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] = i;
dis[i] = -1;
}
bfs(s);
}
private void bfs(int s) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
pre[s] = s;
dis[s] = 0; // 起点的距离标记为0
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]) {
queue.offer(w) ;
pre[w] = v;
visited[w] = true;
dis[w] = dis[v] + 1; // 这里就是距离
}
}
}
}
private boolean isConnectedTo(int t) {
g.validateVertax(t);
return visited[t];
}
public int distance(int t) {
g.validateVertax(t);
return dis[t];
}
public Iterable<Integer> path(int t) {
g.validateVertax(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 g= new Graph("g.txt");
UnweightSingleSourcePathBFS ussp = new UnweightSingleSourcePathBFS(g,0) ;
System.out.println("0-->6: " + ussp.path(6));
System.out.println("0-->6: " +ussp.distance(6));
System.out.println(ussp.isConnectedTo(6));
}
}
小结
BFS 求解的最短路径 , 只能用于无权图 。
深度优先遍历和广度优先遍历之间有什么联系:
非递归的DFS和BFS算法在逻辑的逻辑上一模一样。只是bfs把栈换成了队列。