Course Schedule II:判断有向图是否有环

本文详细解析了课程安排II问题的两种解决方案,一种是通过计算每个顶点的入度并逐步移除入度为0的顶点来确定课程顺序;另一种是采用深度优先搜索的方法,检查是否存在环路,并在没有环的情况下返回有效的课程顺序。

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

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Input: 2, [[1,0]] 
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished   
             course 0. So the correct course order is [0,1] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both     
             courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. 
             So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

思路1:判断每个顶点的入度,每次将入度为0的顶点移除,直至所有顶点均被移除,否则图有环。

思路2:深度优先遍历每个顶点,若访问期间再次访问到正在被当前遍历访问中的顶点,则图有环。visited表示是否正在被访问,discover表示该顶点是否已被深度优先遍历过。(相当于用三种颜色表示节点:未被访问、正在被访问、已经访问完毕三种状态。)

思路二代码:来自:https://leetcode.com/problems/course-schedule-ii/discuss/133808/Java-DFS-beats-99.

class Solution {
    
    boolean[] discovered;
    boolean[] visited;
    int[] resultSet;
    int counter=0;
    
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        
        // Construct adjList first
        List<Integer>[] adjList = constructAdjList(numCourses, prerequisites);
       
        discovered = new boolean[numCourses];
        visited = new boolean[numCourses];
        
        resultSet = new int[numCourses];
        
        for(int i=0; i<numCourses; i++) {
            
            if(!discovered[i]) {
                
                if(adjList[i] == null){
                    discovered[i] = true;
                    resultSet[counter++] = i; // Courses which don't have any prereq can be added in any order.
                    continue;
                }
                
                if(findCycle(i, adjList)) {
                    return new int[0];
                }
                
            }
            
        }
        
        return resultSet;
        
    }
    
    private List<Integer>[] constructAdjList(int n, int[][] prereq) {
        
        List<Integer>[] adjList = new ArrayList[n];
        
        for(int i=0; i<prereq.length; i++) {
            
            int vertex = prereq[i][0];
            int neighbor = prereq[i][1];
            
            if(adjList[vertex] == null) {
                adjList[vertex] = new ArrayList<Integer>();
            }
            
            adjList[vertex].add(neighbor);
            
        }
        
        return adjList;
        
    }
    
    private boolean findCycle(int vertex, List<Integer>[] adjList) {
        
        discovered[vertex] = true;
        visited[vertex] = true;
        
        boolean result = false;
        List<Integer> neighbors = adjList[vertex];
        
        if(neighbors!=null) {  // Important as we are constructing adjList only for vertices available in prerequisites array.
            for(Integer neighbor: neighbors) {

                if(visited[neighbor]) { // back-edge found!
                    result = true;
                    break;
                }

                if(discovered[neighbor]) { // If already discovered, no need to traverse again. Consider other neighbors!
                    continue;
                }

                if(findCycle(neighbor, adjList)) { // Perform DFS.
                    result = true;
                    break;
                }

            }
        }
        
        resultSet[counter++] = vertex; // Add the course to resultSet
        visited[vertex] = false;  // Very important line to find back-edge.
        return result;
        
    }
}

思路一代码是我自己写的,击败了2%的选手,难过

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        //if(prerequisites == null) return null;
        int m = prerequisites.length;
        //if(m <= 0) return null;
        Map<Integer,Set<Integer>> in = new HashMap<Integer,Set<Integer>>();
        Map<Integer,Set<Integer>> out = new HashMap<Integer,Set<Integer>>();
        for(int i = 0 ; i < numCourses ; i++){
            in.put(i,new HashSet<Integer>());
            out.put(i,new HashSet<Integer>());
        }
        for(int i = 0 ; i < m ; i++){            
            in.get(prerequisites[i][0]).add(prerequisites[i][1]);
            out.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }
        List<Integer> ans = new ArrayList<Integer>();
        Set<Integer> temp = new HashSet<Integer>();
        while(true){
            int start = -1;
            for(int i = 0 ; i < numCourses ; i++){
                if(in.get(i).size() == 0 && !temp.contains(i)){
                    start = i;
                    break;
                }
            }
            if(start == -1){
                if(ans.size() == numCourses) {
                    int[] res = new int[numCourses];
                    for(int i = 0 ; i < numCourses;i++){
                        res[i] = ans.get(i);
                    }
                    return res;
                }else{
                     return new int[0];
                }            
            }else{
                ans.add(start); 
                temp.add(start);
                for(int i : out.get(start)){
                    in.get(i).remove(start);
                }            
            }
        }
    }
}


内容概要:该论文探讨了一种基于粒子群优化(PSO)的STAR-RIS辅助NOMA无线通信网络优化方法。STAR-RIS作为一种新型可重构智能表面,能同时反射和传输信号,与传统仅能反射的RIS不同。结合NOMA技术,STAR-RIS可以提升覆盖范围、用户容量和频谱效率。针对STAR-RIS元素众多导致获取完整信道状态信息(CSI)开销大的问题,作者提出一种在不依赖完整CSI的情况下,联合优化功率分配、基站波束成形以及STAR-RIS的传输和反射波束成形向量的方法,以最大化总可实现速率并确保每个用户的最低速率要求。仿真结果显示,该方案优于STAR-RIS辅助的OMA系统。 适合人群:具备一定无线通信理论基础、对智能反射面技术和非正交多址接入技术感兴趣的科研人员和工程师。 使用场景及目标:①适用于希望深入了解STAR-RIS与NOMA结合的研究者;②为解决无线通信中频谱资源紧张、提高系统性能提供新的思路和技术手段;③帮助理解PSO算法在无线通信优化问题中的应用。 其他说明:文中提供了详细的Python代码实现,涵盖系统参数设置、信道建模、速率计算、目标函数定义、约束条件设定、主优化函数设计及结果可视化等节,便于读者理解和复现实验结果。此外,文章还对比了PSO与其他优化算法(如DDPG)的区别,强调了PSO在不需要显式CSI估计方面的优势。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值