ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures & Algorithms
    CC-213
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    CC-213›Adjacency Matrix and Adjacency List Implementations
    Data Structures & AlgorithmsTopic 36 of 37

    Adjacency Matrix and Adjacency List Implementations

    4 minread
    699words
    Beginnerlevel

    Adjacency Matrix and Adjacency List Implementations

    Graphs can be represented in two common ways: adjacency matrices and adjacency lists. Each representation has its own advantages and disadvantages, depending on the nature of the graph and the operations being performed.

    1. Adjacency Matrix

    An adjacency matrix is a 2D array (or matrix) used to represent a graph. For a graph with nnn vertices, it is an n×nn \times nn×n matrix where each cell (i,j)(i, j)(i,j) indicates whether there is an edge from vertex iii to vertex jjj.

    • Matrix Cell Values:
      • 1 (or true) indicates the presence of an edge.
      • 0 (or false) indicates no edge.

    Properties:

    • Space Complexity: O(V2)O(V^2)O(V2), where VVV is the number of vertices.
    • Fast edge lookup: O(1)O(1)O(1) to check if an edge exists between two vertices.
    • Inefficient for sparse graphs (graphs with relatively few edges compared to vertices).

    Example Implementation:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Graph {
    private:
        vector<vector<int>> adjMatrix;
        int numVertices;
    
    public:
        Graph(int vertices) : numVertices(vertices) {
            adjMatrix.resize(vertices, vector<int>(vertices, 0)); // Initialize to 0
        }
    
        void addEdge(int u, int v) {
            adjMatrix[u][v] = 1; // Directed graph
            // adjMatrix[v][u] = 1; // Uncomment for undirected graph
        }
    
        void printGraph() {
            for (int i = 0; i < numVertices; i++) {
                for (int j = 0; j < numVertices; j++) {
                    cout << adjMatrix[i][j] << " ";
                }
                cout << endl;
            }
        }
    };
    
    int main() {
        Graph g(4);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
    
        g.printGraph();
        return 0;
    }
    

    2. Adjacency List

    An adjacency list is a more space-efficient way to represent a graph. It uses an array (or vector) of lists (or vectors), where each index represents a vertex and contains a list of all adjacent vertices (i.e., those with which it shares an edge).

    Properties:

    • Space Complexity: O(V+E)O(V + E)O(V+E), where EEE is the number of edges. This makes it suitable for sparse graphs.
    • Iterating through all edges takes O(E)O(E)O(E) time, which can be more efficient than using an adjacency matrix.

    Example Implementation:

    #include <iostream>
    #include <vector>
    #include <list>
    using namespace std;
    
    class Graph {
    private:
        vector<list<int>> adjList;
        int numVertices;
    
    public:
        Graph(int vertices) : numVertices(vertices) {
            adjList.resize(vertices);
        }
    
        void addEdge(int u, int v) {
            adjList[u].push_back(v); // Directed graph
            // adjList[v].push_back(u); // Uncomment for undirected graph
        }
    
        void printGraph() {
            for (int i = 0; i < numVertices; i++) {
                cout << "Vertex " << i << ":";
                for (int v : adjList[i]) {
                    cout << " -> " << v;
                }
                cout << endl;
            }
        }
    };
    
    int main() {
        Graph g(4);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
    
        g.printGraph();
        return 0;
    }
    

    Summary

    Both adjacency matrices and adjacency lists are effective ways to represent graphs, but they serve different needs:

    • Adjacency Matrix:

      • Use when you need fast edge lookup and the graph is dense (many edges).
      • More straightforward for certain algorithms (e.g., Floyd-Warshall).
    • Adjacency List:

      • Use for sparse graphs to save space and time when iterating through edges.
      • Often more flexible and easier to manipulate.

    Choosing the right representation depends on the specific use case and the characteristics of the graph being modeled.

    Previous topic 35
    Shortest Path
    Next topic 37
    Memory Management and Garbage Collection

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count699
      Code examples0
      DifficultyBeginner