经典题。检验图中是否成环。
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList<Integer>[] graph = new ArrayList[numCourses]; // 每个index表示从哪个出发,index的arraylist包含所有到达的
int[] in = new int[numCourses]; // 每个顶点的入度
for (int i = 0; i < graph.length; ++i) {
graph[i] = new ArrayList();
}
for (int[] p: prerequisites) {
graph[p[1]].add(p[0]);
in[p[0]]++;
}
Queue<Integer> q = new LinkedList();
// for (int i : in) {
// if (i == 0) q.offer(i);
// }
for (int i = 0; i < numCourses; ++i) {
if (in[i] == 0) q.offer(i);
}
while (!q.isEmpty()) {
int pre = q.poll();
for (int post : graph[pre]) {
--in[post];
if (in[post] == 0) q.offer(post);
}
}
for (int i = 0; i < in.length; ++i) {
if (in[i] != 0) return false;
}
return true;
}
}
值得注意的是入度为0的顶点加入q的时候是:
// for (int i : in) {
// if (i == 0) q.offer(i);
// }
for (int i = 0; i < numCourses; ++i) {
if (in[i] == 0) q.offer(i);
}
是遍历所有顶点加入入度为0的顶点,并不是遍历in
入度数组加入这些入度 -- 加入入度0并没有任何意义。这里注意一下。
根据已排序相邻的两个字符串构建Map<Character, Set<Character>>
,同时对每个char保存入度。本质上就是多了一个char->set
的集合。然后还是用q进行BFS拓扑排序。最后根据结果规模和顶点数判断是否成环
class Solution {
public String alienOrder(String[] words) {
Map<Character, Set<Character>> map = new HashMap();
Map<Character, Integer> indegree = new HashMap();
String res = "";
if (words == null || words.length == 0) return res;
for (String s : words) {
for (char c : s.toCharArray()) {
indegree.put(c, 0);
}
}
for (int i = 0; i < words.length - 1; ++i) {
String cur = words[i];
String next = words[i+1];
int len = Math.min(cur.length(), next.length());
for (int j = 0; j < len; ++j) {
char c1 = cur.charAt(j);
char c2 = cur.charAt(j);
if (c1 != c2) { //[c1, c2]有没有记录下来
Set<Character> set = new HashSet();
if (map.containsKey(c1)) set = map.get(c1);
if (!set.contains(c2)){
set.add(c2);
map.put(c1, set);
indegree.put(c2, indegree.get(c2)+1);
}
break;
}
}
}
Queue<Character> q = new LinkedList();
for (char c: indegree.keySet()){
if (indegree.get(c) == 0) q.offer(c);
}
while (!q.isEmpty()) {
char c = q.poll();
res += c;
if (map.containsKey(c)) {
for (char c1 : map.get(c)){
indegree.put(c1, indegree.get(c1)-1);
if (indegree.get(c1) == 0) q.offer(c1);
}
}
}
if (res.length() != indegree.size()) return ""; // non-DAG, loop exists; contradiction
return res;
}
}