题目地址:
https://www.lintcode.com/problem/kill-process/description
给定两个整数数组 A A A和 B B B表示进程名,长度相等,每个位置表示 A [ i ] A[i] A[i]的父进程是 B [ i ] B[i] B[i]。现在给定一个进程 k k k,要求杀死此进程后所有被终止的进程的进程名。某个进程被杀死后其自己和其子孙节点都会被终止。题目保证进程之间父子的关系是森林的形式,也就是没有环。
本质上就是多叉树的搜索。首先建图,然后DFS即可。代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
/**
* @param pid: the process id
* @param ppid: the parent process id
* @param kill: a PID you want to kill
* @return: a list of PIDs of processes that will be killed in the end
*/
public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
// Write your code here
List<Integer> res = new ArrayList<>();
// key表示进程名,value表示其(直接)子进程的进程名
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < pid.size(); i++) {
graph.putIfAbsent(ppid.get(i), new ArrayList<>());
graph.get(ppid.get(i)).add(pid.get(i));
}
dfs(kill, graph, res);
return res;
}
private void dfs(int id, Map<Integer, List<Integer>> graph, List<Integer> res) {
res.add(id);
if (graph.containsKey(id)) {
for (int child : graph.get(id)) {
dfs(child, graph, res);
}
}
}
}
时空复杂度 O ( V + E ) O(V+E) O(V+E)。