Skip to content

Commit 6e31d64

Browse files
committedNov 24, 2016
add one graph question: topological BFS
1 parent c62b78b commit 6e31d64

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
 

‎444_sequenceReconstruction.java

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
public class Solution {
2+
public boolean sequenceReconstruction(int[] org, int[][] seqs) {
3+
HashMap<Integer, Integer> degree = new HashMap<Integer, Integer>();
4+
HashMap<Integer, List<Integer>> graph = new HashMap<Integer, List<Integer>>(); //Using list, not hashSet!!
5+
//seq can be same: [1,2] and [1,2], if using set it will have problem.
6+
7+
for(int[] seq: seqs){
8+
if(seq.length == 1){
9+
if(!degree.containsKey(seq[0])) degree.put(seq[0], 0);
10+
if(!graph.containsKey(seq[0])) graph.put(seq[0], new ArrayList<Integer>());
11+
} else{
12+
for(int i = 0; i < seq.length-1; i++){
13+
int prev = seq[i];
14+
int next = seq[i+1];
15+
if(!degree.containsKey(prev)) degree.put(prev, 0);
16+
if(!degree.containsKey(next)) degree.put(next, 0);
17+
18+
degree.put(next, degree.get(next)+1);
19+
//this is get(next)+1!!! not get(prev), we don't know the gap between prev and next
20+
21+
if(!graph.containsKey(prev)) graph.put(prev, new ArrayList<Integer>());
22+
if(!graph.containsKey(next)) graph.put(next, new ArrayList<Integer>());
23+
graph.get(prev).add(next);
24+
}
25+
}
26+
}
27+
28+
if(degree.size()!= org.length) return false; //first check whether same integer numbers in org and seqs.
29+
30+
Queue<Integer> queue = new LinkedList<Integer>();
31+
for(int key: degree.keySet()){
32+
if(degree.get(key) == 0) queue.add(key);
33+
}
34+
35+
int index = 0;//current org character pointer index
36+
while(!queue.isEmpty()){
37+
int size = queue.size();
38+
if(size > 1) return false; // one degree matches with two integer, which is not allowed.
39+
int temp = queue.remove();
40+
41+
//if index is out of bound return false;
42+
//if org[index] is not equals to current temp, return false;
43+
if(index == org.length || org[index]!= temp) return false;
44+
45+
index++;//dont forget!!!
46+
List<Integer> list = graph.get(temp);
47+
for(int next: list){
48+
degree.put(next, degree.get(next)-1);
49+
if(degree.get(next) == 0) queue.add(next);
50+
}
51+
}
52+
return index == org.length;
53+
}
54+
}

0 commit comments

Comments
 (0)
Please sign in to comment.