zoukankan      html  css  js  c++  java
  • 802. 找到最终的安全状态->拓扑排序,1306. 跳跃游戏 III->dfs,684. 冗余连接->并查集

    对出度为零的点进行拓扑排序


    class Solution {
        public List<Integer> eventualSafeNodes(int[][] graph) {
            List<Integer> ans=new ArrayList<>();
            int[] out = new int[graph.length];
            ArrayList<Integer>[] in = new ArrayList[graph.length];
            for(int i=0; i<graph.length; i++){
                in[i]=new ArrayList<>();
            }
            Queue<Integer> queue = new LinkedList<>();
            for(int i=0; i<graph.length; i++){
                for(int b:graph[i]){
                    out[i]++;
                    in[b].add(i);
                }
                if(graph[i].length==0)
                    queue.offer(i);
            }
            int temp=0;
            while(!queue.isEmpty()){
                temp=queue.poll();
                ans.add(temp);
                for(int i:in[temp]){
                    out[i]--;
                    if(out[i]==0)
                        queue.offer(i);
                }
            }
            Collections.sort(ans);
            return ans;
        }
    }
    


    没啥好说的,dfs一把梭


    class Solution {
        public boolean canReach(int[] arr, int start) {
            boolean[] vis = new boolean[arr.length];
            return dfs(start,arr,vis);
        }
        public boolean dfs(int cur, int[] arr, boolean[] vis){
            vis[cur]=true;
            if(arr[cur]==0)
                return true;
            boolean res=false;
            if(cur+arr[cur]<arr.length&&!vis[cur+arr[cur]])
                res = dfs(cur+arr[cur],arr,vis);
            if(res)
                return res;
            if(cur-arr[cur]>=0&&!vis[cur-arr[cur]])
                res = dfs(cur-arr[cur],arr,vis);
            return res;
        }
    }
    

    并查集裸题,第一个环找到即可


    class Solution {
        public int[] findRedundantConnection(int[][] edges) {
            int[] father = new int[edges.length+1];
            int[] ans = new int[2];
            int a=0,b=0;
            for(int[] edge:edges){
                a=find(father,edge[0]);
                b=find(father,edge[1]);
                if(a==b){
                    ans[0]=Math.min(edge[0],edge[1]);
                    ans[1]=Math.max(edge[0],edge[1]);
                    break;
                }
                father[b]=a;
            }
            return ans;   
        }
        int find(int[] father,int cur){
            if(father[cur]==0)  return cur;
            return (father[cur]=find(father,father[cur]));
        }
    }
    
  • 相关阅读:
    编写简单的c运行库(一)
    c中函数参数传递
    MSVC命令行参数
    在C#中对List<>进行排序
    向DataTable中添加一行数据的做法
    获取本机IP(考虑多块网卡、虚拟机等复杂情况)
    [转]在C#中判断一个文本文件的编码方式
    关于C#使用XML序列化的一些注意事项
    C#中的类型和SQL Server中的类型对应关系
    关于DLL文件和EXE文件不在同一目录下的设置
  • 原文地址:https://www.cnblogs.com/Crossea/p/12844321.html
Copyright © 2011-2022 走看看