Only Path :
判断是否只存在一个拓扑排序的序列 只需要保证队列中一直最多只有1个元素即可
tricky part:
1) org has all the nodes. That is why each time there should only be 1 element in the queue. If it is not, one node is missing. The normal Topology just checked whether all the node could be accessed. It doesn‘t mean one path contains all the node.
2) The seqs probably give the duplicates info for two edges, we need to check whether it is added to set successfully to determine whether we need to increase the degree.
3) The sequence in seqs might only have one element, we need to process it seperately.
4) For the cases like [1] [[][]], we need to be able to rule out them. The edges are stored in the seqs, the mininum seqs length is the same as org. So if org.length is more than the seq.length together in seqs, there are missing information about certain edges. We can directly return false.
public class Solution { /** * @param org a permutation of the integers from 1 to n * @param seqs a list of sequences * @return true if it can be reconstructed only one or false */ public boolean sequenceReconstruction(int[] org, int[][] seqs) { HashMap<Integer, HashSet<Integer>> map = new HashMap<>(); HashMap<Integer, Integer> indgree = new HashMap<>(); for (int i : org) { map.put(i, new HashSet<Integer>()); indgree.put(i, 0); } int n = org.length; int count = 0; for (int[] seq : seqs) { count += seq.length; //System.out.println(seq.length); if (seq.length == 1 && (seq[0] > n || seq[0] < 1)) { return false; } for (int s = 1; s < seq.length; s++) { if (seq[s] > n || seq[s] < 1) { return false; } if (map.get(seq[s - 1]).add(seq[s])) { // this is need to check to avoid duplicate edge indgree.put(seq[s], indgree.get(seq[s]) + 1); } } } if (count < n) { return false; } Queue<Integer> q = new LinkedList<>(); for (int key : indgree.keySet()) { if (indgree.get(key) == 0) { q.offer(key); } } count = 0; while (q.size() == 1) { int num = q.poll(); count++; for (int s : map.get(num)) { // don‘t need check, because of the initial indgree.put(s, indgree.get(s) - 1); if (indgree.get(s) == 0) { q.offer(s); } } } return count == n; } }