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
    COMP2117
    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
    COMP2117›Graphs
    Data StructuresTopic 31 of 37

    Graphs

    5 minread
    915words
    Intermediatelevel

    Graphs

    A graph is a collection of vertices (or nodes) and edges that connect pairs of vertices. Graphs are a fundamental data structure used to represent relationships and connections in various domains, such as social networks, transportation systems, and computer networks.

    Key Components

    1. Vertices (Nodes): The individual elements or points in a graph.
    2. Edges: The connections between the vertices. Edges can be:
      • Directed: The connection has a direction (from vertex A to vertex B).
      • Undirected: The connection is bidirectional (between vertex A and vertex B).
    3. Weighted Edges: Edges that have a value or weight associated with them, representing costs, distances, etc.

    Types of Graphs

    1. Directed Graph (Digraph): A graph where the edges have a direction.
    2. Undirected Graph: A graph where the edges do not have a direction.
    3. Weighted Graph: A graph where each edge has a weight.
    4. Unweighted Graph: A graph where all edges are treated equally (no weights).
    5. Cyclic Graph: A graph that contains at least one cycle (a path that starts and ends at the same vertex).
    6. Acyclic Graph: A graph that does not contain cycles.
    7. Connected Graph: A graph in which there is a path between every pair of vertices.
    8. Disconnected Graph: A graph that has at least two vertices that are not connected by a path.

    Graph Representations

    Graphs can be represented in several ways:

    1. Adjacency Matrix:

      • A 2D array where the cell at row iii and column jjj indicates the presence (or weight) of an edge between vertex iii and vertex jjj.
      • Suitable for dense graphs.
    2. Adjacency List:

      • An array (or list) where each element contains a list of adjacent vertices (and optionally the weights of the edges).
      • More space-efficient for sparse graphs.

    Example: Graph Representation using Adjacency List

    Here’s a simple C++ implementation of a graph using an adjacency list:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Graph {
    private:
        int V; // Number of vertices
        vector<vector<int>> adj; // Adjacency list
    
    public:
        Graph(int v) : V(v), adj(v) {}
    
        void addEdge(int u, int v) {
            adj[u].push_back(v); // Add edge from u to v
            // If undirected, uncomment the next line:
            // adj[v].push_back(u); // Add edge from v to u
        }
    
        void printGraph() {
            for (int i = 0; i < V; ++i) {
                cout << "Vertex " << i << ":";
                for (int j : adj[i]) {
                    cout << " -> " << j;
                }
                cout << endl;
            }
        }
    };
    
    int main() {
        Graph g(5); // Create a graph with 5 vertices
        g.addEdge(0, 1);
        g.addEdge(0, 4);
        g.addEdge(1, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 3);
        g.addEdge(3, 4);
    
        g.printGraph(); // Display the graph
    
        return 0;
    }
    

    Explanation of the Code

    1. Graph Class: Contains the number of vertices and an adjacency list represented as a vector of vectors.
    2. addEdge Function: Adds an edge from vertex uuu to vertex vvv. If the graph is undirected, it adds the reverse edge as well.
    3. printGraph Function: Prints the adjacency list representation of the graph.
    4. Main Function: Demonstrates creating a graph, adding edges, and printing the graph.

    Graph Traversal Algorithms

    Two fundamental algorithms for traversing graphs are:

    1. Depth-First Search (DFS):

      • Explores as far down a branch as possible before backtracking.
      • Can be implemented using recursion or a stack.
    2. Breadth-First Search (BFS):

      • Explores all neighbors of a vertex before moving to the next level.
      • Implemented using a queue.

    Example: Depth-First Search

    Here’s a basic implementation of DFS using the previous graph representation:

    void DFSUtil(int v, vector<bool>& visited) {
        visited[v] = true; // Mark the current vertex as visited
        cout << v << " "; // Process the current vertex
    
        for (int i : adj[v]) {
            if (!visited[i]) {
                DFSUtil(i, visited); // Recur for all adjacent vertices
            }
        }
    }
    
    void DFS() {
        vector<bool> visited(V, false);
        for (int i = 0; i < V; ++i) {
            if (!visited[i]) {
                DFSUtil(i, visited);
            }
        }
    }
    

    Complexity Analysis

    • Space Complexity:

      • Adjacency Matrix: O(V2)O(V^2)O(V2)
      • Adjacency List: O(V+E)O(V + E)O(V+E) where EEE is the number of edges.
    • Time Complexity:

      • DFS: O(V+E)O(V + E)O(V+E)
      • BFS: O(V+E)O(V + E)O(V+E)

    Applications of Graphs

    1. Network Routing: Representing networks and finding optimal paths.
    2. Social Networks: Modeling relationships between users.
    3. Recommendation Systems: Finding connections and similarities between items.
    4. Maps and Navigation: Representing geographical data and finding shortest paths.

    Conclusion

    Graphs are a powerful data structure that can model complex relationships and interactions. Understanding how to represent and traverse graphs is crucial for solving many computational problems, especially in network analysis, data organization, and algorithm design. Mastery of graph concepts enables developers to create efficient solutions in various real-world applications.

    Previous topic 30
    Balanced Trees
    Next topic 32
    Breadth-First Traversal

    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 time5 min
      Word count915
      Code examples0
      DifficultyIntermediate