Complete the code to declare an adjacency matrix for a graph with 5 nodes.
int[][] adjacencyMatrix = new int[[1]][[1]];
The adjacency matrix size is n x n, where n is the number of nodes. For 5 nodes, it is 5x5.
Complete the code to add an edge from node 2 to node 4 in an adjacency list representation.
adjacencyList.get([1]).add(4);
Node indices start at 0 or 1 depending on implementation. Here, adding edge from node 2 means accessing index 2.
Fix the error in the code that checks if an edge exists between node 1 and node 3 using adjacency matrix.
if (adjacencyMatrix[1][[1]] == 1) { System.out.println("Edge exists"); }
To check edge from node 1 to node 3, use adjacencyMatrix[1][3].
Fill both blanks to create an adjacency list for a graph with 4 nodes and add an edge from node 0 to node 2.
List<List<Integer>> adjacencyList = new ArrayList<>(); for (int i = 0; i < [1]; i++) { adjacencyList.add(new [2]<>()); } adjacencyList.get(0).add(2);
We create 4 lists for 4 nodes. ArrayList is a common choice for adjacency lists.
Fill all three blanks to check if an edge exists from node 3 to node 1 in an adjacency list and print a message.
if (adjacencyList.get([1]).[2]([3])) { System.out.println("Edge exists from 3 to 1"); }
To check edge from node 3 to 1, get list at index 3 and check if it contains 1.
