Graph Representation | C++

Introduction to Graphs DSA practice problem on Onlearn.

Difficulty: easy.

Topics: Graph Representation Methods in Memory (Adjacency Matrix and Adjacency List), Graph, Adjacency Matrix, Adjacency List, Edge, Directed Graph, Undirected Graph, Time Complexity, Space Complexity, Arrays, Input/Output Operations, Data Structures, Loops, graph representation, space complexity, graph properties, Graph Representation, Graph Types.

Graph Representation Methods You are given a graph described by its number of nodes and edges, followed by the connections between them. Your task is to implement two common graph representation methods: the Adjacency Matrix and the Adjacency List. After constructing these representations, you should output them in a specified format. The graph can be either undirected or directed, and its nodes are 1 indexed. Input The first line contains three space separated integers: N, M, and GraphType. N denotes the number of nodes (from 1 to N). M denotes the number of edges. GraphType is an integer: 0 for an undirected graph, 1 for a directed graph. The next M lines each contain two space separated integers u and v, representing an edge between node u and node v. Output First, print the Adjacency Matrix representation. The matrix should be an N x N grid. matrix[i][j] should be 1 if an edge exists from i to j, and 0 otherwise. Each row should be printed on a new line, with elements space separated. Then, print the Adjacency List representation. For each node i from 1 to N, print i followed by a space, a colon, a space, and then a space separated list of its adjacent nodes. If a node has no adjacent nodes, print i:. Constraints 1 <= N <= 100 0 <= M <= N (N 1) (maximum edges for directed graph) 1 <= u, v <= N Sample Input 1 (Undirected Graph) Sample Output 1 Sample Input 2 (Directed Graph) Sample Output 2