0
点赞
收藏
分享

微信扫一扫

图【LeetCode】


图【LeetCode】

前言

写作于
2022-11-04 17:28:00

发布于
2022-11-20 16:03:35

图 简单

997. 找到小镇的法官

小镇里有 n 个人,按从 1 到 n 的顺序编号。传言称,这些人中有一个暗地里是小镇法官。

如果小镇法官真的存在,那么:

小镇法官不会信任任何人。
每个人(除了小镇法官)都信任这位小镇法官。
只有一个人同时满足属性 1 和属性 2 。
给你一个数组 trust ,其中 trust[i] = [ai, bi] 表示编号为 ai 的人信任编号为 bi 的人。

如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1 。

示例 1:

输入:n = 2, trust = [[1,2]]
输出:2
示例 2:

输入:n = 3, trust = [[1,3],[2,3]]
输出:3
示例 3:

输入:n = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1

有向图中找出度为0的并且入度为n-1的顶点

class Solution {
//有向图中找出度为0的并且入度为n-1的顶点
public int findJudge(int n, int[][] trust) {
int[] inDegrees=new int[n+1];//容纳1-n个人
int[] outDegrees=new int[n+1];
for(int[] edge:trust){
int x=edge[0],y=edge[1]; //只有两个元素,信任和被信任
outDegrees[x]++;
inDegrees[y]++;
}
for(int i=1;i<=n;i++){
if(inDegrees[i]==n-1&&outDegrees[i]==0){
return i;
}
}

return -1;
}
}

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

有一个具有 n 个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。

请你确定是否存在从顶点 source 开始,到顶点 destination 结束的 有效路径 。

给你数组 edges 和整数 n、source 和 destination,如果从 source 到 destination 存在 有效路径 ,则返回 true,否则返回 false 。

bfs 起点是source,看visited[destination]==true?

用邻接表来存储,邻接矩阵超出内存限制

class Solution {
List<Integer>[] adjacentArr;
boolean[] visited;

public boolean validPath(int n, int[][] edges, int source, int destination) {
adjacentArr = new List[n];
for (int i = 0; i < n; i++) {
adjacentArr[i] = new ArrayList<Integer>();
}
for (int[] edge : edges) {
adjacentArr[edge[0]].add(edge[1]);
adjacentArr[edge[1]].add(edge[0]);
}
visited = new boolean[n];
return dfs(source, destination);
}

public boolean dfs(int vertex, int destination) {
visited[vertex] = true;
if (!visited[destination]) {
List<Integer> adjacent = adjacentArr[vertex];
for (int next : adjacent) {
if (!visited[next] && dfs(next, destination)) {
return true;
}
}
}
return visited[destination];
}
}


举报

相关推荐

0 条评论