701247. Print adjacency list
Here is a detailed Markdown blog post for the GeeksforGeeks problem:
Print Adjacency List
Slug: print-adjacency-list-1587115620 Difficulty: Easy Id: 701247 Topic Tags: Graph, Data Structures Company Tags: None
Summary
The problem involves printing the adjacency list representation of a given graph. The key concepts involved are graph theory and data structures.
Detailed Explanation
To print the adjacency list of a graph, we first need to understand what an adjacency list is. It is a representation of a graph where each node is associated with a list of its neighboring nodes. In other words, for each node, we store all its adjacent nodes.
Here's a step-by-step breakdown of the solution:
- Start by initializing an empty dictionary (or map) to represent the adjacency list.
- Iterate through each node in the graph.
- For each node, iterate through its neighboring nodes and add them to the adjacency list.
- Finally, print out the adjacency list.
Here's a sample output for an adjacency list of a graph with three nodes A, B, C:
A -> [B]
B -> [C, A]
C -> []
In this representation, each node is associated with a list of its neighboring nodes. Time complexity for printing the adjacency list is O(V + E) where V is the number of vertices and E is the number of edges in the graph.
Space complexity is also O(V + E) as we need to store all the vertices and edges in the adjacency list.
Optimized Solutions
Java
import java.util.*;
public class Main {
public static void printAdjacencyList(int[][] graph) {
Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
for (int i = 0; i < graph.length; i++) {
adjacencyList.put(i, new ArrayList<>());
for (int j = 0; j < graph[i].length; j++) {
if (graph[i][j] == 1) {
adjacencyList.get(i).add(j);
}
}
}
for (Map.Entry<Integer, List<Integer>> entry : adjacencyList.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
public static void main(String[] args) {
int[][] graph = {{0, 1}, {1, 2}, {2, 0}};
printAdjacencyList(graph);
}
}