Leetcode(easy Graph)

Leetcode(Graph)

leetcode 图的简单题目

997 找到小镇的法官

题解 这是一道关于图的基本知识的题目,入度与出度的使用。符合题目要求的人一定是出度为0,入度为N-1

class Solution{
	public int findJudge(int N,int[][] trust){
		int[] indegree = new int[N+1];
		int[] outdegree = new int[N+1];
		for(int[] info:trust){
			int out = info[0];
			int in = info[1];
			indegree[in]++;
			outdegree[out]++;
	}
	for(int i = 0;i<N+1;i++) if(indegree[i]==N-1 && outdegree[i]==0) return i;
	return -1;
}

1042 不邻接种花

使用dfs,创建一个全局的数组colored用于记录每一个花园栽种的花的种类,dfs:遍历一个点的时候,先判断是否已经种植了鲜花,如果种植了,就直接返回,如果没有种植鲜花就选择一个颜色种植上去,并记录colored,知道全部的节点都被便利即可。

class Solution {
    List<List<Integer>> graph;
    int[] colored;
    public int[] gardenNoAdj(int n, int[][] paths) {
        graph = new LinkedList<List<Integer>>();
        colored = new int[n+1];
        for(int i = 0;i<n+1;i++) graph.add(new LinkedList<Integer>());
        for(int[] info:paths){
            graph.get(info[0]).add(info[1]);
            graph.get(info[1]).add(info[0]);
        }
        for(int i = 1;i<n+1;i++) dfs(i);
        int[] res = new int[n];
        for(int i = 0;i < n;i++) res[i] = colored[i+1];
        return res;

    }
    public void dfs(int n){
        if(colored[n] != 0) return;
        int[] record = new int[5];
        for(int node:graph.get(n)) record[colored[node]]=1;
        for(int i = 0;i<record.length;i++) if(record[i]==0) colored[n]=i;
        for(int node:graph.get(n)){
            dfs(node);
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值