Search code examples
javagraphdepth-first-searchvertex

Get neighbouring vertices only using depth first search


How to get neighbouring vertices only using depth first search?

I am using depth first search algorithm to search a Directed Graph, my problem is that I want to make it only return the neighbors of my start vertex, instead it keeps carrying on until it reaches a dead end.

So lets say I have vertices (A, B, C, D) And edges ((A -> B), (A -> C), (C -> D)) And I want all neighbors of Vertex A, instead of getting B and C it is also including D even though D is not Adjacent to A?

  public void dfs(int x)  // depth-first search
  {                                 // begin at vertex 0
  vertexList[x].wasVisited = true;  // mark it
  displayVertex(x);                 // display it
  theStack.push(x);                 // push it

  while( !theStack.isEmpty() )      // until stack empty,
     {
     // get an unvisited vertex adjacent to stack top
     int v = getAdjUnvisitedVertex( theStack.peek() );
     if(v == -1)                    // if no such vertex,
        theStack.pop();
     else                           // if it exists,
        {
        vertexList[v].wasVisited = true;  // mark it
        displayVertex(v);                 // display it
        theStack.push(v);                 // push it
        }
     }  // end while

  // stack is empty, so we're done
  for(int j=0; j<nVerts; j++)          // reset flags
     vertexList[j].wasVisited = false;
  }  // end dfs
  // ------------------------------------------------------------
  // returns an unvisited vertex adj to v
public int getAdjUnvisitedVertex(int v)
  {
  for(int j=0; j<nVerts; j++)
     if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
        return j;
        System.out.println("Found unvisited vertex");
  return -1;
  }  // end getAdjUnvisitedVertex()

I understand I could just store the neighbors of a Vertex when creating it but then that means I will have to make a lot of changes if I had to make changes in the future, if anyone has any ideas on how to guide me in the right direction I would be very grateful!!


Solution

  • If you represent your graph as the adjecency matrix then you should just can just take all entries that are non zero from the row corresponding to vertex A.

    for(int j=0; j<nVerts; j++)
     if(adjMat[v][j]==1) System.out.println("vertex " + j);
    

    so you do not need dfs for that.