【算法】图类基础算法题解,LeeCode997. 找到小镇的法官,LeetCode1791. 找出星型图的中心节点,LeetCode1971. 寻找图中是否存在路径

LeeCode997. 找到小镇的法官

LeeCode997. 找到小镇的法官

class Solution {
    public int findJudge(int n, int[][] trust) {
        // indeg = n - 1
        // outdeg = 0
		
        int[] indeg = new int[n + 1];
        int[] outdeg = new int[n + 1];

        for (int[] t : trust) {
            int x = t[0];
            int y = t[1];
            indeg[y]++;
            outdeg[x]++;
        }
        // 找到出度是0,入度是 n-1的点
        for (int i = 1; i <= n; i++) {
            if (indeg[i] == n - 1 && outdeg[i] == 0) return i;
        }
        return -1;
    }
}

LeetCode1791. 找出星型图的中心节点

LeetCode1791. 找出星型图的中心节点

class Solution {
    public int findCenter(int[][] edges) {
        // 建图,找到入度为 edges.length的点
        int n = edges.length + 1;

        int[] indeg = new int[n + 1];

        for (int[] edge : edges) {
            int x = edge[0];
            int y = edge[1];
            // 双向边,入度都++
            indeg[x]++;
            indeg[y]++;
        }

        for (int i = 1; i <= n; i++) {
            if (indeg[i] == edges.length) return i;
        }
        return -1;
    }
}

LeetCode1971. 寻找图中是否存在路径

LeetCode1971. 寻找图中是否存在路径

class Solution {
    List<List<Integer>> to = new ArrayList<>();
    boolean[] visited;
    int destination;
    boolean ans;

    public boolean validPath(int n, int[][] edges, int source, int destination) {
        // 起点和终点相同直接返回
        if (source == destination) return true;

        visited = new boolean[n];
        this.destination = destination;
        ans = false;

        for (int i = 0; i < n; i++) {
            to.add(new ArrayList<>());
        }

        // 建图
        for (int[] edge : edges) {
            int x = edge[0];
            int y = edge[1];
            to.get(x).add(y);
            to.get(y).add(x);
        }

        dfs(source, -1);
        return ans;
    }

    void dfs(int x, int fa) {
        visited[x] = true;

        for (int y : to.get(x)) {
            if (fa == y) continue;
            if (!visited[y]) dfs(y, x);
            // 找到目标 返回true
            if (y == destination) ans = true;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值