Mark As Completed Discussion

To represent a graph in code, there are several ways to do it. One common way is to use an Adjacency List, which is an array of lists. Each element in the array represents a vertex in the graph, and the list at that index contains all the adjacent vertices. This representation works well when the graph is sparse, meaning it has fewer edges compared to the maximum number of edges.

For example, let's say we have a graph with 5 vertices and the following edges:

  • Vertex 0 is connected to vertices 1 and 4
  • Vertex 1 is connected to vertices 0, 2, 3, and 4
  • Vertex 2 is connected to vertices 1 and 3
  • Vertex 3 is connected to vertices 1, 2, and 4
  • Vertex 4 is connected to vertices 0, 1, and 3

Here's how we can represent this graph using an adjacency list in Java:

TEXT/X-JAVA
1class Main {
2    public static void main(String[] args) {
3        // Adjacency List representation of a graph
4        int V = 5;
5        ArrayList<ArrayList<Integer>> graph = new ArrayList<>(V);
6
7        for (int i = 0; i < V; i++) {
8            graph.add(new ArrayList<>());
9        }
10
11        // Add edges
12        graph.get(0).add(1);
13        graph.get(0).add(4);
14        graph.get(1).add(0);
15        graph.get(1).add(2);
16        graph.get(1).add(3);
17        graph.get(1).add(4);
18        graph.get(2).add(1);
19        graph.get(2).add(3);
20        graph.get(3).add(1);
21        graph.get(3).add(2);
22        graph.get(3).add(4);
23        graph.get(4).add(0);
24        graph.get(4).add(1);
25        graph.get(4).add(3);
26
27        // Print the graph
28        for (int i = 0; i < V; i++) {
29            System.out.println("Adjacency list of vertex " + i + ": ");
30            System.out.print("head");
31            for (Integer j : graph.get(i)) {
32                System.out.print(" -> " + j);
33            }
34            System.out.println();
35        }
36    }
37}

In this code, we first initialize an empty adjacency list graph with 5 elements. Then, we add edges to the graph by accessing the lists at the corresponding indices and adding the adjacent vertices. Finally, we print the adjacency list representation of the graph. You can run this code to see the output.

This is just one way to represent a graph in code. There are other representations like Adjacency Matrix and Edge List, which have their own advantages and disadvantages depending on the problem at hand. It's important to choose the appropriate representation based on the characteristics of the graph and the operations you need to perform on it.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment