|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +class Solution { |
| 4 | + static Map<Integer,List<Integer>> adjList = new HashMap<>(); |
| 5 | + static Map<Integer,Boolean> visited = new HashMap<>(); |
| 6 | + static Set<Integer> startCandidate = new TreeSet<>(); |
| 7 | + static Set<Integer> noStart = new TreeSet<>(); |
| 8 | + static int[] answer = new int[4]; |
| 9 | + |
| 10 | + public int[] solution(int[][] edges) { |
| 11 | + |
| 12 | + for(int[] edge : edges){ |
| 13 | + List<Integer> temp; |
| 14 | + if(adjList.containsKey(edge[0])){ |
| 15 | + startCandidate.add(edge[0]); |
| 16 | + temp = adjList.get(edge[0]); |
| 17 | + }else{ |
| 18 | + temp = new ArrayList<>(); |
| 19 | + } |
| 20 | + temp.add(edge[1]); |
| 21 | + adjList.put(edge[0],temp); |
| 22 | + visited.put(edge[0],false); |
| 23 | + visited.put(edge[1],false); |
| 24 | + } |
| 25 | + for(int[] edge : edges){ |
| 26 | + if(startCandidate.contains(edge[1])){ |
| 27 | + noStart.add(edge[1]); |
| 28 | + } |
| 29 | + } |
| 30 | + for(int start : startCandidate){ |
| 31 | + if(!noStart.contains(start)){ |
| 32 | + answer[0] = start; |
| 33 | + break; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + for(int start : adjList.get(answer[0])){ |
| 38 | + BFS(start); |
| 39 | + } |
| 40 | + return answer; |
| 41 | + } |
| 42 | + public void BFS(int start){ |
| 43 | + ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 44 | + q.offer(start); |
| 45 | + visited.put(start,true); |
| 46 | + |
| 47 | + while(!q.isEmpty()){ |
| 48 | + int cur = q.poll(); |
| 49 | + if(adjList.get(cur) == null){ |
| 50 | + answer[2]++; |
| 51 | + return; |
| 52 | + } |
| 53 | + for(int next : adjList.get(cur)){ |
| 54 | + if(adjList.get(next) == null){ |
| 55 | + answer[2]++; |
| 56 | + return; |
| 57 | + } |
| 58 | + if(adjList.get(next).size() == 2){ |
| 59 | + answer[3]++; |
| 60 | + return; |
| 61 | + } |
| 62 | + if(visited.get(next)){ |
| 63 | + answer[1]++; |
| 64 | + return; |
| 65 | + } |
| 66 | + q.offer(next); |
| 67 | + visited.put(next,true); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments