andres
andres

Reputation: 321

Attempting to implement DFS in Java

Attempting to implement a DFS algorithm to this Adjacent Graph class. I am having trouble implementing the sudo-code into Java. I have seen some examples implement an int array to store a visited value, and other examples that use a boolean array to store the visisted value. Some insight on the pros and cons to these design choices would be appreciated.

    DFS()
       count = 0 
       for each vertex v in V do
          if v is marked with 0 
              dfs(v)

    dfs(v)
        count = count +1 
        for each vertex w in V adjacent to v do
            if w is makred with 0
              dfs(w)

    public class AdjGraphDFS 
    {   
        private int     v;
        private int     counter;
        private int     [] visited;
        private boolean [][] adj;

        public boolean directed;

        public AdjGraphDFS( int vector )
        {
            v = vector; 
            adj = new boolean[ v ][ v ];        
        }

        public void addEdge( int u, int v )
        {
            if( directed == true )
            {
                adj[u][v] = true;
            }

            else
            {   
                adj[v][u] = true;
                adj[u][v] = true;
            }
        }
    // This is where I fail to implement DFS logic correctly
    public void DFS()
        {
            counter = 0;
            for ( int i = 0; i < adj.length; i++)
            {
                if( visited[i] == 0)
                {
                    dfs(v);
                }
            }       
        }

Here is my attempt at implementing the recursive dfs(v) 

        // and this is where I fail to implement dfs( v ) correctly 
        public void dfs( int v )
        {       
            ++counter;
            for(int i = 0; i < adj.length; i++)
            {           
                if( /* w is unvisited */)
                {
                    dfs(v);
                    visited[i] = counter;
                }

                System.out.println( "Visiting vertex " + v );
            }       

here

Upvotes: 0

Views: 726

Answers (1)

mutaflux
mutaflux

Reputation: 51

You are not checking that w is a neighbor for v. Also you need to mark vertice as visited before the recursive call. Your loop should look like

// println("Visiting " + v);

for(int i = 0; i < adj.length; i++)
{           
    if( adj[v][i] && (visited[i] == 0) )
    {
        visited[i] = counter;
        dfs(i);
    }
}

Upvotes: 1

Related Questions