Learn basic data structures in ten days - Day 7 (Graph)

Insert image description here

Basic concepts of graphs

A graph is a data structure used to represent relationships between objects. It consists of two basic components:

  • Vertex : Also known as node, represents an object or entity in the graph.

  • Edge : A line connecting two vertices, representing the relationship between vertices.

The difference between directed and undirected graphs

Graphs can be divided into two main types:

  • Undirected Graph : The edges have no direction, indicating that the relationship between two vertices is bidirectional. Imagine a social network graph between you and your friends. This is an example of an undirected graph.

  • Directed Graph : The edges have directions, indicating that the relationship from one vertex to another vertex is one-way. A typical example of a directed graph is a web page link graph, where arrows represent link directions.

Graph traversal method

Traversing a graph means visiting all vertices and edges in the graph. Two common graph traversal methods are as follows:

  • Depth First Search (DFS) : DFS starts from the starting vertex, follows a path as deep as possible until it can no longer continue, and then backtracks to other paths. This approach is similar to exploring, keep going until there are no paths left unexplored.

  • Breadth-First Search (BFS) : BFS starts from the starting vertex, first visits all directly adjacent vertices, and then expands outward layer by layer. This method is similar to water wave diffusion in that the area closest to the starting point is first explored and then gradually expanded to further areas.

Task

Create and manipulate graph data structures, and understand graph traversal algorithms.

Example code - Create a simple undirected graph using C++:

#include <iostream>
#include <vector>

class Graph {
    
    
public:
    Graph(int vertices) : V(vertices) {
    
    
        adj = std::vector<std::vector<int>>(vertices);
    }

    void addEdge(int v, int w) {
    
    
        adj[v].push_back(w);
        adj[w].push_back(v);
    }

    void printGraph() {
    
    
        for (int v = 0; v < V; ++v) {
    
    
            std::cout << "顶点 " << v << " 的邻居: ";
            for (const int& neighbor : adj[v]) {
    
    
                std::cout << neighbor << " ";
            }
            std::cout << std::endl;
        }
    }

private:
    int V; // 顶点数
    std::vector<std::vector<int>> adj; // 邻接表
};

int main() {
    
    
    Graph g(5); // 创建一个具有5个顶点的图

    // 添加边
    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();

    return 0;
}

operation result: Insert image description here

Practice questions :

  1. Explain the basic concepts of vertices and edges in graphs.

  2. What are directed and undirected graphs? Can you give a real-life example?

  3. Describe how depth-first search (DFS) and breadth-first search (BFS) work.

  4. You can design a simple diagram that represents the social relationships between you and your friends. Use C++ to create this graph and implement DFS or BFS to find relationship paths between friends.

Explain the basic concepts of vertices and edges in graphs.

  • Vertices : Vertices are also known as nodes, they are basic elements in a graph and represent objects or entities. In a social network, each person can be represented as a vertex.

  • Edge : An edge is a line connecting two vertices and represents the relationship between the vertices. In a social network, if two people are friends, an edge can be used to represent this relationship.

What are directed and undirected graphs? Can you give a real-life example?

  • Directed graph : In a directed graph, the edges have directions, which means that the relationship from one vertex to another vertex is one-way. For example, the following relationship in Twitter is a directed graph, in which user A follows user B, but not necessarily the other way around.

  • Undirected graph : In an undirected graph, the edges have no direction, indicating that the relationship between two vertices is bidirectional. For example, the friend relationship on Facebook can be represented by an undirected graph. If user A is a friend of user B, then user B is also a friend of user A.

Describe how depth-first search (DFS) and breadth-first search (BFS) work.

  • DFS (Depth First Search) : DFS starts from the starting vertex, follows a path as deep as possible until it can no longer continue, and then backtracks to other paths. It is implemented using stack data structure or recursion. DFS is similar to following a branch down to the bottom, then going back and exploring other branches.

  • BFS (Breadth First Search) : BFS starts from the starting vertex, first visits all directly adjacent vertices, and then expands outward layer by layer. It is implemented using a queue data structure. BFS is similar to water wave diffusion. It first explores the area closest to the starting point and then gradually expands to farther areas.

You can design a simple diagram that represents the social relationships between you and your friends. Use C++ to create this graph and implement DFS or BFS to find relationship paths between friends.

This is a simple C++ example code that takes a social graph and performs DFS to find relationship paths between friends. Note that this is just an example and social graphs in real applications are often more complex.

#include <iostream>
#include <vector>
#include <queue>

class Graph {
    
    
public:
    Graph(int vertices) : V(vertices) {
    
    
        adj = std::vector<std::vector<int>>(vertices);
    }

    void addEdge(int v, int w) {
    
    
        adj[v].push_back(w);
        adj[w].push_back(v);
    }

    void DFS(int start, int target, std::vector<bool>& visited, std::vector<int>& path) {
    
    
        visited[start] = true;
        path.push_back(start);

        if (start == target) {
    
    
            // 找到目标,打印路径
            std::cout << "关系路径: ";
            for (int vertex : path) {
    
    
                std::cout << vertex << " ";
            }
            std::cout << std::endl;
        } else {
    
    
            for (int neighbor : adj[start]) {
    
    
                if (!visited[neighbor]) {
    
    
                    DFS(neighbor, target, visited, path);
                }
            }
        }

        // 回溯
        visited[start] = false;
        path.pop_back();
    }

private:
    int V; // 顶点数
    std::vector<std::vector<int>> adj; // 邻接表
};

int main() {
    
    
    Graph socialNetwork(7); // 创建一个具有7个顶点的社交关系图

    // 添加社交关系边
    socialNetwork.addEdge(0, 1);
    socialNetwork.addEdge(0, 2);
    socialNetwork.addEdge(1, 3);
    socialNetwork.addEdge(1, 4);
    socialNetwork.addEdge(2, 5);
    socialNetwork.addEdge(3, 6);

    std::vector<bool> visited(7, false);
    std::vector<int> path;

    std::cout << "查找朋友之间的关系路径:" << std::endl;
    socialNetwork.DFS(0, 6, visited, path); // 查找从顶点0到顶点6的关系路径

    return 0;
}

operation result: Insert image description here

Note: This sample code demonstrates how to create a social graph and use DFS to find relationship paths between friends. In practical applications, social networks may contain more vertices and more complex relationships.

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/133554790