ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2117Graphs
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2117

    Data Structures

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    5 min read
    Topic 31 of 37
    Topic Study Note Illustration
    31

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    915words
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures