0

I want to write pseudo-code for visiting a state machine using DFS. State machine can be considered as a directed graph. Following algorithm from Cormen book uses a DFS algorithm to visit a graph.

DFS-VISIT(G, u)          //G= graph, u=root vertex
    u.color = GRAY
    for each v from G.Adjacents(u)   //edge (u, v)
        if v.color == WHITE
            DFS-VISIT(G, v)

State machine however can have multiple edges between the two vertices. And above algorithm stores edges in an adjacency list. I have implemented the algorithm in Java with following classes,

class Node{
    String name;
    ....
    ArrayList<Transition> transitions;

    void addTransition(Transition tr);
}

class Transition 
{
    String src;
    String dest;
}

With the above given information, I have built a state machine with node and transition objects. I want to modify the above algorithm where I don't have a graph object G. I just have access to root object.

Can I modify the above algorithm like below?

DFS-VISIT(root)                //root node
    root.color = GRAY
    for each t from root.getTransitions()  //t=transition
        v = t.getDestination()        //v=destination of t
        if v.color == WHITE
            DFS-VISIT(v)
Dominique Fortin
  • 2,212
  • 15
  • 20
Junaid
  • 1,668
  • 7
  • 30
  • 51

1 Answers1

1

The algorithm is independent of implementation. Actually, it's the other way around. The question you should be asking is this: "do your proprietary implementation has all the exact properties that are required by the algorithm?"

The algorithm has very few strict demands. You need a set of nodes and a set of edges, where each edge connects 2 nodes. That's the generic definition of graph. How you acquire, store and process these sets is irrelevant to the algorithm. For the algorithm step all you need is access to a given node from the set and access to a set of its neighbors. What you've presented seems fine (of course, for the next step you'll need to progress to the next node after root).

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85