图的深度优先遍历的六种应用附Java代码

news/2024/7/15 20:13:17 标签: 深度优先, 图论, 算法, 数据结构, java, 开发语言

目录

无向图的连通分量个数

单纯求出了连通分量个数 

能具体返回哪几个点是同一个连通分量

路径问题

单源路径问题

从某个顶点到另一个顶点的路径问题

检测无向图中的环

二分图的检测


无向图的连通分量个数

单纯求出了连通分量个数 

java">import java.util.ArrayList;

public class CC {

    private Graph G;
    private int[] visited;
    private int cccount = 0;

    public CC(Graph G){

        this.G = G;
        visited = new int[G.V()];
        for(int i = 0; i < visited.length; i ++)
            visited[i] = -1;

        for(int v = 0; v < G.V(); v ++)
            if(visited[v] == -1){
                dfs(v, cccount);
                cccount ++;
            }
    }

    private void dfs(int v, int ccid){

        visited[v] = ccid;
        for(int w: G.adj(v))
            if(visited[w] == -1)
                dfs(w, ccid);
    }

    public int count(){
//        for(int e: visited)
//            System.out.print(e + " ");
//        System.out.println();
        return cccount;
    }

    public boolean isConnected(int v, int w){
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components(){

        ArrayList<Integer>[] res = new ArrayList[cccount];
        for(int i = 0; i < cccount; i ++)
            res[i] = new ArrayList<Integer>();

        for(int v = 0; v < G.V(); v ++)
            res[visited[v]].add(v);
        return res;
    }

    public static void main(String[] args){

        Graph g = new Graph("g.txt");
        CC cc = new CC(g);
        System.out.println(cc.count());

        System.out.println(cc.isConnected(0, 6));
        System.out.println(cc.isConnected(5, 6));

        ArrayList<Integer>[] comp = cc.components();
        for(int ccid = 0; ccid < comp.length; ccid ++){
            System.out.print(ccid + " : ");
            for(int w: comp[ccid])
                System.out.print(w + " ");
            System.out.println();
        }
    }
}

能具体返回哪几个点是同一个连通分量

java">import java.util.ArrayList;

public class CC{
  private Graph G;
  private boolean[] visited;
  private int cccount = 0;
public CC(Graph G){
    this.G = G;
  visited = new int[G.V()];
for(int i = 0; i < visited.length; i++)
{
         visited[i] = -1;
}
for(int v = 0; v < G.V(); v++){
   if(visited[V] == -1){
      dfs(v, ccount);
      cccount++;
   }
  }
private void dfs(int v, int ccid){
   visited[v] = ccid;
for(int w : G.adj(v)){
   if(visited[w] == -1){
       dfs(w, ccid);
    }
   }
  }
public int count(){
   for(int e : visited){
    System.out.print(e + " ");
}
   System.out.println();
   return cccount;
  }
public static void main(String[] args){
 Graph g = new Graph("g.txt");
 CC cc = new GraphDFS(g);
 System.out.println(cc.count());
  }
 }
}

路径问题

单源路径问题

java">import java.util.ArrayList;
import java.util.Collections;

public class SingleSourcePath {

    private Graph G;
    private int s;

    private int[] pre;

    public SingleSourcePath(Graph G, int s){

        this.G = G;
        this.s = s;
        pre = new int[G.V()];
        for(int i = 0; i < pre.length; i ++)
            pre[i] = -1;

        dfs(s, s);
    }

    private void dfs(int v, int parent){

        pre[v] = parent;
        for(int w: G.adj(v))
            if(pre[w] == -1)
                dfs(w, v);
    }

    public boolean isConnectedTo(int t){
        G.validateVertex(t);
        return pre[t] != -1;
    }

    public Iterable<Integer> path(int t){

        ArrayList<Integer> res = new ArrayList<Integer>();
        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");
        SingleSourcePath sspath = new SingleSourcePath(g, 0);
        System.out.println("0 -> 6 : " + sspath.path(6));
        System.out.println("0 -> 5 : " + sspath.path(5));
    }
}

从某个顶点到另一个顶点的路径问题

java">import java.util.ArrayList;
import java.util.Collections;

public class Path {

    private Graph G;
    private int s, t;

    private int[] pre;
    private boolean[] visited;

    public Path(Graph G, int s, int t){

        G.validateVertex(s);
        G.validateVertex(t);

        this.G = G;
        this.s = s;
        this.t = t;

        visited = new boolean[G.V()];
        pre = new int[G.V()];
        for(int i = 0; i < pre.length; i ++)
            pre[i] = -1;

        dfs(s, s);
        for(boolean e: visited)
            System.out.print(e + " ");
        System.out.println();
    }

    private boolean dfs(int v, int parent){

        visited[v] = true;
        pre[v] = parent;

        if(v == t) return true;

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

    public boolean isConnected(){
        return visited[t];
    }

    public Iterable<Integer> path(){

        ArrayList<Integer> res = new ArrayList<Integer>();
        if(!isConnected()) 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");
        Path path = new Path(g, 0, 6);
        System.out.println("0 -> 6 : " + path.path());

        Path path2 = new Path(g, 0, 5);
        System.out.println("0 -> 5 : " + path2.path());

        Path path3 = new Path(g, 0, 1);
        System.out.println("0 -> 1 : " + path3.path());
    }
}

检测无向图中的环

思路:找到一个已经被访问过的结点,并且这个结点不是当前节点的上一个结点。

java">public class CycleDetection {

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

    public 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;
                }
    }

    // 从顶点 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.txt");
        CycleDetection cycleDetection = new CycleDetection(g);
        System.out.println(cycleDetection.hasCycle());

        Graph g2 = new Graph("g2.txt");
        CycleDetection cycleDetection2 = new CycleDetection(g2);
        System.out.println(cycleDetection2.hasCycle());
    }
}

二分图的检测

思路:从某一点开始逐个染色。

 

 

java">import java.util.ArrayList;

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(!dfs(v, 0)){
                    isBipartite = false;
                    break;
                }
    }

    private boolean dfs(int v, int color){

        visited[v] = true;
        colors[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.txt");
        BipartitionDetection bipartitionDetection = new BipartitionDetection(g);
        System.out.println(bipartitionDetection.isBipartite);
        // true

        Graph g2 = new Graph("g2.txt");
        BipartitionDetection bipartitionDetection2 = new BipartitionDetection(g2);
        System.out.println(bipartitionDetection2.isBipartite);
        // false

        Graph g3 = new Graph("g3.txt");
        BipartitionDetection bipartitionDetection3 = new BipartitionDetection(g3);
        System.out.println(bipartitionDetection3.isBipartite);
        // true
    }
}

http://www.niftyadmin.cn/n/5138004.html

相关文章

技术学习群-第五期内容共享

本期是技术学习群第五期知识共享。对外免费开放。私聊即可。欢迎各位加入。 一起看看本期分享了些啥知识。 关于Python第三方装包-pandas 群友有提问&#xff1a; 这个问题还是比较明显的&#xff0c;直接将 Microsoft Visual C 14.0 下载安装即可。随后她又遇到了一个问题&…

Flutter 开发、测试,网络调试工具

一、Github地址 NetworkCapture 二、效果图 三、使用方式 添加pub依赖latest_version dependencies:network_capture: ^latest_versionChange your App to NetworkCaptureApp void main() {runApp(NetworkCaptureApp(enable: true,navigatorKey: navigatorKey,child: cons…

Linux网络编程02

UDP协议 UDP协议处于传输层&#xff0c;是不可靠谱、无连接、消息有边界的协议 TCP类似于管道&#xff0c;UDP类似于队列 UDP头部 传输层头部都不需要IP地址&#xff0c;都只需要端口号 Berkeley Socket&#xff08;库&#xff09; Berkeley Scoket 库已经完成了传输层之下…

考试成绩这样分发

老师们&#xff0c;还在为每次繁琐的成绩查询而头痛&#xff1f;今天我就要给大家带来一个超级实用的教程&#xff0c;让你轻松解决这个问题&#xff01; 我来介绍一下这个神秘的“成绩查询页面”。别以为它很复杂&#xff0c;其实它就是一个简单的网页&#xff0c;上面会有每个…

如何通过会员营销数字化推动精准营销与用户忠诚度培养?

营销策略的制定和实施对于企业的成功至关重要&#xff0c;而会员数字化营销系统将通过用户画像、会员标签等重要功能&#xff0c;推动企业提高用户忠诚度培养。目前市面上有哪些热门的会员营销功能&#xff1f; 一、用户画像&#xff1a;让营销更精准 用户画像是一种通过收集和…

RocketMQ学习笔记(三)

集成SpringBoot 基础配置 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath/> <!-- lookup parent from repos…

弱覆盖栅格图层制作

栅格边界生成及图层制作 栅格边界polygon生成 提取的弱覆盖栅格数据中包含了栅格中心经度和栅格中心维度&#xff0c;我们根据栅格中心经纬度生成对应的栅格边界POLYGON&#xff08;20米*40米&#xff09; 计算公式&#xff1a;polygon(栅格中心经度-0.00017 栅格中心纬度0.00…

发现个好玩的 Windows微信对话框换行

按住shift键按enter就是换行 直接按enter为发送