ProblemSet of Graph Algorithms

本文深入解析了课程安排问题中的两种核心算法:深度优先搜索(DFS)和Kahn's算法。通过详细阐述这两种算法如何应用于课程先修条件的检查与排序,帮助读者理解如何判断课程是否能顺利完成以及获取合理的课程学习顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分图算法

import java.util.Scanner;
 
public class Main
{
    public static int n_vertex;
    public static int n_edges;
    public static int[][] adjMatrix;
    public static int[] color;
     
    public static boolean dfs(int v,int c)
    {
        color[v]=c;
        for(int i=1;i<=n_vertex;i++)
        {
            if(adjMatrix[v][i]==1)
            {
                if(color[i]==c)
                    return false;
                if(color[i]==0 && !dfs(i,-c))
                    return false;
            }
        }
        return true;
    }
     
     
    public static String solve()
    {
        for(int i=1;i<=n_vertex;i++)
        {
            if(color[i]==0)
            {
                if(!dfs(i,1))
                {
                    return "No";
                }
            }
        }
        return "Yes";
    }
     
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        n_vertex=in.nextInt();
        n_edges=in.nextInt();
        color=new int[n_vertex+1];
        adjMatrix=new int[n_vertex+1][n_vertex+1];
        for(int i=0;i<n_edges;i++)
        {
            int start=in.nextInt();
            int end=in.nextInt();
            adjMatrix[start][end]=1;
            adjMatrix[end][start]=1;
        }
        System.out.println(solve());
    }
}

207. Course Schedule
图的拓扑排序
算法一:dfs

class Solution {
    
    public static int[] visitStatus;
    public static ArrayList<ArrayList<Integer>> adjList;
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        
        
        adjList=new ArrayList<>();
        visitStatus=new int[numCourses];
        for(int i=0;i<numCourses;i++)
            adjList.add(new ArrayList<>());
        
        for(int[] tmp:prerequisites)
        {
            adjList.get(tmp[1]).add(tmp[0]);
        }
        
        for(int i=0;i<numCourses;i++)
        {
            if(visitStatus[i]!=0)
                continue;
            if(!dfs(i))
                return false;
        }
        return true;
    }
    
    
    public static boolean dfs(int i)
    {
        visitStatus[i]=1;
        for(int j=0;j<adjList.get(i).size();j++)
        {
            int m=adjList.get(i).get(j);
            if(visitStatus[m]==2)
                continue;
            if(visitStatus[m]==1)
                return false;
            if(!dfs(m))
                return false;
        }
        visitStatus[i]=2;
        return true;
    }
}

算法二:Kahn’s algorithm

class Solution {
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {

   
        int[] indegrees=new int[numCourses];
        ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
        for(int i=0;i<numCourses;i++)
            adj.add(new ArrayList<>());  
        
        for(int[] tmp:prerequisites)  //邻接表构建
        {
            adj.get(tmp[1]).add(tmp[0]);
            indegrees[tmp[0]]++;
        }
        Queue<Integer> q=new LinkedList<>();
        for(int i=0;i<numCourses;i++){
            if(indegrees[i]==0)
                q.add(i);
        }
        int cnt=0;
        ArrayList<Integer> ans=new ArrayList<>();
        while(!q.isEmpty())
        {
            int tmp=q.poll();
            ans.add(tmp);
            for(int i:adj.get(tmp)){
                if(--indegrees[i]==0)
                    q.add(i);
            }
            cnt++;
        }
        return cnt==numCourses;
    }
}

210. Course Schedule II
算法一:dfs

class Solution {
    
    
    public static int[] reversePost;
    public static int idx;
    public static int[] visitStatus;
    public static ArrayList<ArrayList<Integer>> adjList;//邻接表
    
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        
        idx=numCourses-1;
        reversePost=new int[numCourses];
        
        adjList=new ArrayList<>();
        visitStatus=new int[numCourses];
        for(int i=0;i<numCourses;i++)
            adjList.add(new ArrayList<>());
        
        for(int[] tmp:prerequisites)
        {
            adjList.get(tmp[1]).add(tmp[0]);
        }
        
        for(int i=0;i<numCourses;i++)
        {
            if(visitStatus[i]!=0)
                continue;
            if(!dfs(i))
                return new int[0];
        }
        return reversePost;
        
    }
    
    public static boolean dfs(int i)
    {
        visitStatus[i]=1;
        for(int j=0;j<adjList.get(i).size();j++)
        {
            int m=adjList.get(i).get(j);
            if(visitStatus[m]==2)
                continue;
            if(visitStatus[m]==1)
                return false;
            if(!dfs(m))
                return false;
        }
        visitStatus[i]=2;
        reversePost[idx--]=i;
        return true;
    }
    
}

算法二:

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] indegrees=new int[numCourses];
        ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
        for(int i=0;i<numCourses;i++)
            adj.add(new ArrayList<>());  
        
        for(int[] tmp:prerequisites)  //邻接表构建
        {
            adj.get(tmp[1]).add(tmp[0]);
            indegrees[tmp[0]]++;
        }
        Queue<Integer> q=new LinkedList<>();
        for(int i=0;i<numCourses;i++){
            if(indegrees[i]==0)
                q.add(i);
        }
        int cnt=0;
        int[] ans=new int[numCourses];
        while(!q.isEmpty())
        {
            int tmp=q.poll();
            ans[cnt]=tmp;;
            for(int i:adj.get(tmp)){
                if(--indegrees[i]==0)
                    q.add(i);
            }
            cnt++;
        }
        return cnt==numCourses?ans:new int[0];
    }
}

1136. Parallel Courses
实际上也是在做拓扑排序

class Solution {
    public int minimumSemesters(int N, int[][] relations) {
        
        ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
        int[] indegrees=new int[N];
        for(int i=0;i<N;i++)
            adj.add(new ArrayList<>());  
        
        for(int[] tmp:relations)  //邻接表构建
        {
            adj.get(tmp[0]-1).add(tmp[1]-1);
            indegrees[tmp[1]-1]++;
        }
        Queue<Integer> q=new LinkedList<>();
        for(int i=0;i<N;i++){
            if(indegrees[i]==0)
                q.add(i);
        }
        int ans=0;
        while(!q.isEmpty())
        {
           int n=q.size();
            for(int i=0;i<n;i++){
                
                int tmp=q.poll();
                N--;
                for(int v:adj.get(tmp)){
                    if(--indegrees[v]==0){
                        q.add(v);
                    }
                }
            }
            ans++;
        }
        
        return N==0?ans:-1;
    }
}
Graph Algorithms: Practical Examples in Apache Spark and Neo4j By 作者: Mark Needham – Amy E. Hodler ISBN-10 书号: 1492047686 ISBN-13 书号: 9781492047681 Edition 版本: 1 出版日期: 2019-01-04 pages 页数: (217) Discover how graph algorithms can help you leverage the relationships within your data to develop more intelligent solutions and enhance your machine learning models. You’ll learn how graph analytics are uniquely suited to unfold complex structures and reveal difficult-to-find patterns lurking in your data. Whether you are trying to build dynamic network models or forecast real-world behavior, this book illustrates how graph algorithms deliver value—from finding vulnerabilities and bottlenecks to detecting communities and improving machine learning predictions. This practical book walks you through hands-on examples of how to use graph algorithms in Apache Spark and Neo4j—two of the most common choices for graph analytics. Also included: sample code and tips for over 20 practical graph algorithms that cover optimal pathfinding, importance through centrality, and community detection. Learn how graph analytics vary from conventional statistical analysis Understand how classic graph algorithms work, and how they are applied Get guidance on which algorithms to use for different types of questions Explore algorithm examples with working code and sample datasets from Spark and Neo4j See how connected feature extraction can increase machine learning accuracy and precision Walk through creating an ML workflow for link prediction combining Neo4j and Spark
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值