Skip to main content
2 of 6
Fixed formatting
200_success
  • 145.7k
  • 22
  • 191
  • 481

Depth First Search & Breadth First search implementation in java

Implemented DFS and BFS but want to check if code is readable, any issues? Can I improve it?

Here is the code:

Graph.java:

package graphs;

public class Graph {

    public int count; // num of vertices
    private Node vertices[];
    
    public Graph()
    {
        vertices = new Node[8];
        count = 0;
    }

    public void addNode(Node n)
    {
        if(count < 10)
        {
            vertices[count] = n;
            count++;
        }
        else
        {
            System.out.println("graph full");
        }
    }
    
    public Node[] getNode()
    {
        return vertices;
    }
}

Node.java:

package graphs;
import graphs.State;
public class Node {
    
    public Node[] child;
    public int childCount;
    private String vertex;
    public State state;
    
    public Node(String vertex)
    {
        this.vertex = vertex;
    }
    
    public Node(String vertex, int childlen)
    {
        this.vertex = vertex;
        childCount = 0;
        child = new Node[childlen];
    }
    
    public void addChildNode(Node adj)
    {
        adj.state = State.Unvisited;
        if(childCount < 30)
        {
            this.child[childCount] = adj;
            childCount++;
        }
    }
    
    public Node[] getChild()
    {
        return child;
    }
    
    public String getVertex()
    {
        return vertex;
    }

}

State.java:

package graphs;

public enum State {
    
    Unvisited,Visiting,Visited;

}
fscore
  • 634
  • 1
  • 7
  • 15