public class Graph
{

    boolean[][] adjMat;  

    // In the adjacency matrix representation of a Graph,
    // if adjMat[i][j] == true, then you can move from 
    // node i to node j.
    // i.e. j is a neighbour of i.

    // The constructor builds the adjacency matrix,
    // with initially all values false.
    public Graph(int size)
    {
        adjMat = new boolean[size][size];
        for (int i=0; i < adjMat.length; i++)
        {
            for (int j=0; j < adjMat.length; j++)
            {
                adjMat[i][j] = false;
            }
        }     
    }

    // Add a transition to the adjacency matrix,
    // i.e. a neighbour relation between two nodes.
    public void add(int from, int to)
    {
        adjMat[from][to] = true;
    }

    // Carry out uninformed search of the Graph,
    // from the start node to goal node.
    public boolean search(int start, int goal, boolean dp)
    {
        // The frontier is an ArrayList of Paths.
        ArrayList<Path> frontier = new ArrayList<Path>();

        // Initially the frontier contains just the Path
        // containing only the start node.
        Path firstPath = new Path(start);        
        frontier.add(firstPath);

        // Search until the goal is found,
        // or the frontier is empty.
        while (! frontier.isEmpty())
        {
         // *** TO-DO ***
         // CARRY OUT DEPTH-FIRST OR BREADTH-FIRST SEARCH

        }   

        return false;
    }

    public static void main(String[] args)
    {
        // Create a Graph containing 7 nodes
        Graph g = new Graph(7);

        // Add edges to the Graph
        g.add(0, 1);
        g.add(0, 2);
        g.add(1,5);
        g.add(1,6);
        g.add(2, 3);
        g.add(3, 4);

        // select a search type
        boolean depthFirst = false;

        // start searching
        g.search(0,4, depthFirst);
    }
}

Recommended Answers

All 4 Replies

Very interesting. Did you just want to share that, or is there a question?

this is a question i want its answer, its an iincomplete code of dfs

it would be great if you help me

Yes, we will help. But we won't do it for you. You need to explain what you have done so far with your dfs, and why/where you have got stuck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.