LeeCode997. 找到小镇的法官
LeeCode997. 找到小镇的法官
class Solution {
public int findJudge ( int n, int [ ] [ ] trust) {
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] ++ ;
}
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) {
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) ;
if ( y == destination) ans = true ;
}
}
}