图论系列(四)——图的深度优先遍历的应用2

1. 图的环检测

无向图有环:

  1. 当前点的邻接节点已经被访问过
  2. 被访问过的邻接节点不是当前节点的上个访问
import java.util.ArrayList;
import java.util.Collections;

public class CycleDetection {

    private Graph G;
    private boolean[] visited;
    private boolean hasCycle = false;

    CycleDetection(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];

        //解决非连通图的遍历问题
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v])
                if(dfs(v, v)){
                    hasCycle = true;
                    break;
                }
        }
        //dfs(s, s);
    }

    //当前节点v出发是否有环
    private boolean dfs(int v, int parent) {
        visited[v] = true;

        for (int w : G.adj(v)) {
            if (!visited[w])
                if(dfs(w, v))
                    return true;
            else if(w != parent)
                return true;
        }

        return false;
    }

    public boolean hasCycle(){
        return hasCycle;
    }

    public static void main(String[] args) {

        Graph g = new Graph("g_4.txt");
        CycleDetection cycleDetection = new CycleDetection(g);
        System.out.println(cycleDetection.hasCycle());
    }
}

  • 判断一张图是否是一棵树
  1. 图中没环
  2. 图联通

2. 二分图检测

在这里插入图片描述
对于非联通图,只要每个连通分量是一个二分图,整体就一定是一个二分图

import java.util.ArrayList;

public class BipartitionDetection {

    private Graph G;

    private boolean[] visited;
    private int[] colors;       //colors[i]:节点i的颜色:0、1
    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(!dfs(v, 0)){
                    isBipartite = false;
                    break;
                }
    }

    private boolean dfs(int v, int color){

        visited[v] = true;
        colors[v] = color;          //节点v染成color

        for(int w: G.adj(v))
            if(!visited[w]){
                if(!dfs(w, 1 - color)) return false;
            }
            else if(colors[w] == colors[v])     //当前节点与访问过的邻接节点颜色一致
                return false;
        return true;
    }

    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args){

        Graph g = new Graph("g_4_1.txt");
        BipartitionDetection bipartitionDetection = new BipartitionDetection(g);
        System.out.println(bipartitionDetection.isBipartite());
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值