Graph Representation | Java
Introduction to Graphs DSA practice problem on Onlearn.
Difficulty: easy.
Topics: Binary Search Algorithm: Concept and Implementation in Java, Graph, Adjacency Matrix, Adjacency List, Time Complexity, Space Complexity, iterative algorithms, complexity analysis, array, divide and conquer, binary search, recursion.
Given a graph described by its number of nodes and a list of edges, your task is to construct and display its representation using both an adjacency list and an adjacency matrix. Input Specification: The first line contains two space separated integers, N and M, representing the number of nodes and the number of edges, respectively. Nodes are numbered from 1 to N. The next M lines each contain two space separated integers, u and v, indicating an an undirected edge between node u and node v. Output Specification: First, print the adjacency list representation. Each line should start with the node number, followed by a colon, and then a space separated list of its neighbors, sorted in ascending order. After the adjacency list, print the adjacency matrix representation. Each row represents a node, and each column represents a potential neighbor. Print '1' if an edge exists, '0' otherwise, with elements separated by a single space. Constraints: 1 <= N <= 100 0 <= M <= N (N 1) / 2 1 <= u, v <= N u != v (no self loops) The graph is undirected and simple (no multiple edges between the same pair of nodes). Sample Test Cases: Input: Expected Output (Adjacency List): Expected Output (Adjacency Matrix):