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]));
    }
}
posted @ 2020-05-07 17:20  CrosseaLL  阅读(122)  评论(0编辑  收藏  举报