BREADTH-FIRST-SEARCH(G,v)
Q←new Queue()
visited←[]
Q.enqueue(v)
WHILE Q is not empty
u←q.dequeue()
IF u is not in visited
visited.append(u)
FOR all edges, e, from u
Q.enqueue(e.to)
RETURN visited
DEPTH-FIRST-SEARCH (G, v)
S←new Stack()
visited←[]
S.push(v)
WHILE S is not empty
u←S.pop()
IF u is not in visited
visited.append(u)
FOR all edges, e, from u, S.push(e.to)
RETURN visited
Can someone explain the for loop for this pseudocode, i understand everything else but the for loop has got me confused.
Related
For a given node in Directed Acyclic Graph I want to get list of all the ancestors of that node such that they are satisfying precedence order
Let this is an DAG representing tasks and and their precding order.
Now suppose I want to do work E. Then I have to do work [A, B] first.
Hence for input DAG and node E output should be [A, B].
I want an algorithm for this.
To find ancestors of specific target vertex:
dfs(v):
mark v as visited
for every neighbor u of v:
if u is unvisited:
if u is target vertex:
return true
if dfs(u) is true:
put u in result set
return true
else
if u is in result set:
return true
return false
for every unvisited vertex v:
if dfs(v) is true:
put v in result set
return result set
O(V + E) time complexity.
Topological sort: That'll give you the required ordering for all the vertices in O(V + E) time complexity.
Let G be an undirected graph. Consider a depth-first traversal of G, and let T be the resulting depth-first search tree. Let u be a vertex in G and let v be the first new (unvisited) vertex visited after visiting u in the traversal. Which of the following statements is always true?
(A) {u,v} must be an edge in G, and u is a descendant of v in T
(B) {u,v} must be an edge in G, and v is a descendant of u in T
(C) If {u,v} is not an edge in G then u is a leaf in T
(D) If {u,v} is not an edge in G then u and v must have the same parent in T.
=========================================================================
Correct answer is (C)
But I'm stuck at (B), I'm not getting any counter example for (B)
Consider the following graph (which is in fact a tree).
G := (V, E) where
V := {a, u, v} and E := {{a,u}, {a,v}}.
A depth-first traversal in G can visit first a, then u and finally v. At the point where u is visited, v is the next unvisited node. However, {u, v} is not an edge in E, hence statement (B) is false.
There is a directed graph G = [V ; E] with edge weights w(u, v) for (u, v) ∈ E.
Suppose the values for {d[v], π[v]}; v ∈ V and claims
that these are the length of the shortest path and the predecessor node in
it for v ∈ V , how could I verify if this statement is true or false that does not solve the entire shortest path problem from scratch? This is an problem I met with not many ideas in my head ..
The problem is a bit unclear, but to clarify:
There's a node s in your graph, and that for each vertex v:
for v != s, pi[v] is intended to be a node adjacent to v that's on a shortest path from v to s.
d[v] is intended to store the shortest distance from v to s.
The problem is to verify, given a pi, d, that they legitimately contain back-edges and minimal distances.
An easily implemented condition that verifies this is as follows:
For each vertex v
Either:
v = s and d[v] = 0
Or:
d[pi[v]] = d[v] - 1
d[u] >= d[v] - 1 for each u adjacent to v
pi[v] is adjacent to v
This check runs in O(V + E) time.
I wrote this pseudocode to create a spanning tree from a non oriented graph (G,V), where S is a stack and v is the vertex from which we want to start the computation:
PROCEDURE SPANNING-TREE(G,v)
S := {v}
while S is not empty
u := pop(S)
visit u
for each u' connected to u
if u' is not visited
s.push(u')
add-edge(u,u')
For some reason this algorithm is wrong. For example let's consider this simple non oriented graph:
If we start from the first vertex, we visit it and then we push 2 and 3 into the stack and we create two edges: (1,2) and (1,3). Then we visit 3, and since it is connected to 2 which hasn't been visited yet, we also create an edge (3,2), but this creates a cycle so the computed spanning tree is not a tree. Where'e the mistake? I cannot figure another way of computing a spanning tree in O(n).
You can just mark a vertex as visited when you push it to the stack, not when you pop it.
This would be my code. Here visited[] is a boolean array or hashtable
PROCEDURE SPANNING-TREE(G, v)
S := {v}
visited[v] := true
while S is not empty
u := pop(S)
for each u' connected to u
if u' is not visited
visited[u'] := true
s.push(u')
add-edge(u, u')
I am having a tough time understanding Tarjan's lowest common ancestor algorithm. Can somebody explain it with an example?
I am stuck after the DFS search, what exactly does the algorithm do?
My explanation will be based on the wikipedia link posted above :).
I assumed that you already know about the union disjoint structure using in the algorithm.
(If not please read about it, you can find it in "Introduction to Algorithm").
The basic idea is every times the algorithm visit a node x, the ancestor of all its descendants will be that node x.
So to find a Least common ancestor (LCA) r of two nodes (u,v), there will be two cases:
Node u is a child of node v (vice versa), this case is obvious.
Node u is ith branch and v is the jth branch (i < j) of node r, so after visit node u, the algorithm backtrack to node r, which is the ancestor of the two nodes, mark the ancestor of node u as r and go to visit node v.
At the moment it visit node v, as u is already marked as visited (black), so the answer will be r. Hope you get it!
I will explain using the code from CP-Algorithms:
void dfs(int v)
{
visited[v] = true;
ancestor[v] = v;
for (int u : adj[v]) {
if (!visited[u]) {
dfs(u);
union_sets(v, u);
ancestor[find_set(v)] = v;
}
}
for (int other_node : queries[v]) {
if (visited[other_node])
cout << "LCA of " << v << " and " << other_node
<< " is " << ancestor[find_set(other_node)] << ".\n";
}
}
Let's outline a proof of the algorithm.
Lemma 1: For each vertex v and its parent p, after we visit v from p and union v with p, p and all vertices in the subtree of root v (i.e. p and all descendents of v, including v) will be in one disjoint set represented by p (i.e. ancester[root of the disjoint set] is p).
Proof: Suppose the tree has height h. Then proceed by induction in vertex height, starting from the leaf nodes.
Lemma 2: For each vertex v, right before we mark it as visited, the following statements are true:
Each v's parents pi will be in a disjoint set that contains precisely pi and all vertices in the subtrees of pi that pi has already finished visiting.
Every visited vertex so far is in one of these disjoint sets.
Proof: We proceed by induction. The statement is vacuously true for the root (the only vertex with height 0) as it has no parent. Now suppose the statement holds for every vertex of height k for k ≥ 0, and suppose v is a vertex of height k + 1. Let p be v's parent. Before p visits v, suppose it has already visited its children c1, c2, ..., cn. By Lemma 1, p and all vertices in the subtrees of root c1, c2, ..., cn are in one disjoint set represented by p. Furthermore, all newly visited vertices after we visited p are the vertices in this disjoint set. Since p is of height k, we can use the induction hypothesis to conclude that v indeed satisfies 1 and 2.
We are now ready to prove the algorithm.
Claim: For each query (u,v), the algorithm outputs the lowest common ancester of u and v.
Proof: Without loss of generality suppose we visit u before we visit v in the DFS. Then either v is a descendent of u or not.
If v is a descedent of u, by Lemma 1 we know that u and v are in one disjoint set that is represented by u, which means ancestor[find_set(v)] is u, the correct answer.
If v is not a descendent of u, then by Lemma 2 we know that u must be in one of the disjoint sets, each of them represented by a parent of v at the time we mark v. Let p be the representing vertex of the disjoint set u is in. By Lemma 2 we know p is a parent of v, and u is in a visited subtree of p and therefore a descendent of p. These are not changed after we have visited all v's children, so p is indeed a common ancestor of u and v. To see p is the lowest common ancestor, suppose q is the child of p of which v is a descendent (i.e. if we travel back to root from v, q is the last parent before we reach p; q can be v). Suppose for contradiction that u is also a descendent of q. Then by Lemma 2 u is in both the disjoint set represented by p and the disjoint set represented by q, so this disjoint set contains two v's parents, a contradiction.