muregii / codeKenya

10 stars 14 forks source link

Graph implementation from Scratch #41

Open Kennedylelei opened 6 months ago

Kennedylelei commented 6 months ago

public class Graphs{

private class Node {
    private String label;

    public Node(String label) {
        this.label = label;
    }

    @Override
    public String toString(){
        return label;
    }

}

private Map<String, Node> nodes = new HashMap<>();
private Map<Node, List<Node>> adjacencyList = new HashMap<>();

    public void addNode(String label){
        var node =  new Node(label);
        nodes.putIfAbsent(label, node);
         adjacencyList.putIfAbsent(node, new ArrayList<>());

    }

    public void addEdge(String from, String to){
        var fromNode = nodes.get(from);
        if(fromNode == null)
            throw new IllegalArgumentException();

        var toNode = nodes.get(to);
        if(toNode == null)
            throw new IllegalArgumentException();

        adjacencyList.get(fromNode).add(toNode);

    }

    public void print(){
        for(var source : adjacencyList.keySet()) {
            var targets = adjacencyList.get(source);

            if(!targets.isEmpty())
            System.out.println(source +  " is connected to " + targets);
        }
    }
muregii commented 6 months ago

private class Node { private String label;

public Node(String label) {
    this.label = label;
}

@Override
public String toString(){
    return label;
}

}

This is the Node class, used to define label and its constructor and an Override of the toString() method that returns the name of the label.

muregii commented 6 months ago

The Implementation seems to use two HashMaps, one with string and nodes, possibly the "Nodes" themselves. While the other , a Node and a list of other nodes, this is most likely the Linked List.

private Map<String, Node> nodes = new HashMap<>(); private Map<Node, List> adjacencyList = new HashMap<>();