I am currently learning dynamic programming and i can't figure this problem out. Could someone give me an algorithm for it? : Consider a directed graph G = (V,E) where each edge is labeled with a character from an alphabet Sigma, and we designate a special vertex s as the start vertex, and another f as the final vertex. We say that G accepts a string A = a1a2 . . . an if there is a path from s to f of n edges whose labels spell the sequence A. Design an O((|V | + |E|)n) dynamic programming algorithm to determine whether or not A is accepted by G.
Asked
Active
Viewed 739 times
0
-
What have you tried so far? Can you explain us some of your reasoning for this problem? – BlackBear Jun 20 '14 at 10:49
-
Imagine you follow the first edge. What subproblem you then have to solve? – user189 Jun 20 '14 at 11:14
-
I am not following. You are basically describing an [FSM](http://en.wikipedia.org/wiki/Finite-state_machine) (Finite State Machine / automaton). Note that you cannot really say if A is accepted or note without reading A, so the complexity will have to be (at least) `O(S+V+E)`, where `S` is the length of `A`. – amit Jun 20 '14 at 11:15
-
@user189 This problem does seem like a DP one but a backtracking one . In this case backtracking will give u solution in O(|E|*n) – Vikram Bhat Jun 20 '14 at 11:26
-
1@amit In case it is a deterministic FSM, a string will be accepted or rejected in O(S). In case the graph represents a non deterministic FSM, it can be transformed into a deterministic FSM once and then we are back to O(S). – Tarik Jun 20 '14 at 11:51
1 Answers
3
Let
first (str) return the first letter of str
Let len(str) return the length of str
Let rem(str) return str with the first character stripped off.
func (str, v1) =
true if
len(str)=0 and s == f
or
func(rem(str), v2) is true for any v2 such that there exists an edge connecting v1, v2 labeled first(str)
The values of f (str, v) can be memoised to avoid unnecessary recursive calls.

Tarik
- 10,810
- 2
- 26
- 40
-
concise answer, but (1) where do you return `false` (2) the FSM is edge-labelled, so checking `v2 == first(str)` is a bit weird. maybe `label(edge(v1,v2)) == first(str)`. – Apiwat Chantawibul Jun 20 '14 at 16:56
-
Sorry for the first remark, now I see where `false` value originate. – Apiwat Chantawibul Jun 20 '14 at 17:09
-
@Billiska Thanks for your remark. For some reason, I thought that the vertices held the labels. Corrected my answer accordingly. As for being concise, I generally do not believe in spoon feeding, especially for what appears to be a students' homework. – Tarik Jun 20 '14 at 17:51