Mark As Completed Discussion

In graph theory, a graph is a collection of nodes connected by edges. It is a powerful data structure that represents relationships between objects.

The nodes in a graph can be any type of object, and the edges represent connections or relationships between the nodes. Graphs can be used to model various real-world scenarios, such as social networks, transportation networks, and computer networks.

Here's an example of creating a graph in Java:

TEXT/X-JAVA
1class Node {
2  public int value;
3  public List<Node> neighbors;
4
5  public Node(int value) {
6    this.value = value;
7    this.neighbors = new ArrayList<>();
8  }
9}
10
11public class Graph {
12  public List<Node> nodes;
13
14  public Graph() {
15    this.nodes = new ArrayList<>();
16  }
17
18  public void addNode(Node newNode) {
19    this.nodes.add(newNode);
20  }
21}
22
23public class Main {
24  public static void main(String[] args) {
25    // Creating a graph
26    Graph graph = new Graph();
27
28    Node nodeA = new Node(1);
29    Node nodeB = new Node(2);
30    Node nodeC = new Node(3);
31    Node nodeD = new Node(4);
32
33    nodeA.neighbors.add(nodeB);
34    nodeA.neighbors.add(nodeC);
35    nodeB.neighbors.add(nodeD);
36    nodeC.neighbors.add(nodeD);
37
38    graph.addNode(nodeA);
39    graph.addNode(nodeB);
40    graph.addNode(nodeC);
41    graph.addNode(nodeD);
42  }
43}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment