Untitled

mail@pastecode.io avatar
unknown
java
a year ago
1.1 kB
1
Indexable
Never
package LAB9;
import java.util.ArrayList;
import java.util.List;

public class Graph
{
    List<GraphNode> nodeList;

    // Constructor
    public Graph()
    {
        nodeList = new ArrayList<>();
    }

    // Add a node to the graph
    public void addNode(GraphNode node)
    {
        nodeList.add(node);
    }

    // Add an edge between two nodes with a weight
    public void addEdge(GraphNode from, GraphNode to, int weight)
    {
        GraphEdge edge1 = new GraphEdge(from, to, weight);
        from.addEdge(edge1);
        to.addEdge(edge1);

        // Add the edge in the opposite direction
        GraphEdge edge2 = new GraphEdge(to, from, weight);
        to.addEdge(edge2);
        from.addEdge(edge2);
    }

    // Method to print the graph
    public void printGraph()
    {
        for (GraphNode node : nodeList)
        {
            System.out.print("Node " + node.label + " is connected to: ");
            for (GraphEdge edge : node.edgeList)
            {
                System.out.print(edge.toNode.label + "(" + edge.weight + ") ");
            }
            System.out.println();
        }
    }
}