试图用Java实现DFS

时间:2014-11-08 04:40:15

标签: java algorithm graph logic depth-first-search

尝试对此Adjacent Graph类实施DFS算法。我在将sudo-code实现为Java时遇到了麻烦。我已经看到一些示例实现了一个int数组来存储一个访问值,以及其他使用布尔数组存储访问值的示例。对这些设计选择的利弊有所了解,我们将不胜感激。

    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 );
            }       

这里

1 个答案:

答案 0 :(得分:1)

您没有检查w是否是v的邻居。此外,您需要在递归调用之前将vertice标记为已访问。你的循环应该看起来像

// println("Visiting " + v);

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