输入是int[][] input, input[0]是input[1] 的parent,比如 {{1,4}, {1,5}, {2,5}, {3,6}, {6,7}}会形成上面的图
public int findEarliestAncestor(int[][] edges, int node)
{
Map<Integer, Set<Integer>> map = new HashMap<>();
for(int i = 0; i< edges.length; i++)
{
int parent = edges[i][0];
int child = edges[i][1];
map.putIfAbsent(child, new HashSet<Integer>());
map.get(child).add(parent);
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> path = new HashSet<Integer>();
queue.offer(node);
path.add(node);
int earliestAncestor = node;
while(!queue.isEmpty())
{
int size = queue.size();
for(int i = 0; i< size; i++)
{
int current = queue.poll();
earliestAncestor = current;
for(Integer nextElement: map.get(current))
{
if(!path.contains(nextElement))
{
queue.offer(nextElement);
path.add(nextElement);
}
}
}
}
return earliestAncestor;
}