由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 求问一题G家的面经
相关主题
path sum II OJ 超时请教一道面试题
Tree的traversal也分BFS和DFS?又有leetcode题目来请教了
求教一下,我的这个代码有什么问题请问一个java的问题(leetcode subsets一题)
请问一道关于binary tree的题请教Social Graph一题
Amazon Interview QuestionFacebook Phone Inteview + 流程请教
一道G题再上到题
问一个graph题一道面试题
Depth-First-Search自己写了个graph的class但是不work 求指点
相关话题的讨论汇总
话题: visited话题: integer话题: list话题: node话题: path
进入JobHunting版参与讨论
1 (共1页)
n*******e
发帖数: 37
1
给一个directed graph,要求打印出所有的环。
不知道我的Java code可行吗? 我用DFS traverse, 同时记住现在的path, 当侦测到
back edge时, 就打印出path中的cycle部分。
public void printCyclesInDirectedGraph(int n, int[] edges) {
List> graph = new ArrayList>(n);
for (int i = 0; i < n; i++)
graph.add(new LinkedList());
for (int [] e : edges)
graph.get(e[0]).add(e[1]);
int[] visited = new int[n];
for (int i = 0; i < n; i++) {
if (visited[i] == 0) {
List path = new ArrayList(n);
dfs(i, visited, graph, path);
}
}
}
private void dfs(int node, int[] visited,
List> graph, List path) {
path.add(node);
// mark the node as visited and on the current path.
visited[node] = 2;
for (int child : graph.get(node)) {
if (visited[child] == 2) {
// if the child is on the current path,
// then we found a back edge.
// so print the cycle.
print(child, path);
} else if (visited[child] == 0) {
// the child is not visited yet.
dfs(child, visited, graph, path);
}
}
// mark the node as visited, but not on the path.
visited[node] = 1;
path.remove(path.size() - 1);
}
private print(int node, List path) {
// print the cycle in the path.
// start from the node, and stop when encounter the same node.
System.out.println(node);
for (int i = path.size() - 1; path.get(i) != node; i--) {
System.out.println(", " + path.get(i));
}
}
1 (共1页)
进入JobHunting版参与讨论
相关主题
自己写了个graph的class但是不work 求指点Amazon Interview Question
问一个面试题一道G题
问道leetcode的题:Combination Sum II问一个graph题
为啥大家都说刷题无用呢Depth-First-Search
path sum II OJ 超时请教一道面试题
Tree的traversal也分BFS和DFS?又有leetcode题目来请教了
求教一下,我的这个代码有什么问题请问一个java的问题(leetcode subsets一题)
请问一道关于binary tree的题请教Social Graph一题
相关话题的讨论汇总
话题: visited话题: integer话题: list话题: node话题: path