search
HomeBackend DevelopmentC++Query whether vertices X and Y are in the same connected component of an undirected graph

Query whether vertices X and Y are in the same connected component of an undirected graph

Graph theory covers the study of connected components, which are subgraphs in an undirected graph where every pair of vertices is linked by a path and no other vertex is connected to it.

In this article, we will delve into how to use the C/C programming language to determine whether two vertices X and Y belong to the same connected component in an undirected graph. We will clarify the syntax and rationale of the method before clarifying at least two different ways to solve this problem. In addition, we will provide specific code examples and their corresponding results for each method.

grammar

The provided code snippet declares three functions in C for graphical representation. The isConnected function takes two vertices X and Y and returns a Boolean value indicating whether they belong to the same connected component. The addEdge function takes two vertices X and Y and creates a connection between them in the graph. The InitializeGraph function takes an integer value n as input and sets up a graph with n vertices. These functions can be executed using various graph algorithms, such as depth-first search or breadth-first search, to check the connectivity of two vertices and establish connections between vertices in the graph.

bool isConnected(int X, int Y)
{
   // Code to check if X and Y are in the same connected component
   // Return true if X and Y are in the same connected component, false otherwise
}

void addEdge(int X, int Y)
{
   // Code to add an edge between vertices X and Y in the graph
}
void initializeGraph(int n)
{
   // Code to initialize the graph with 'n' vertices
}

algorithm

Step 1 - Use the initialize Graph function to initialize the graph with the specified number of vertices.

Step 2 - Use the addEdge function to add edges between vertices

Step 3 - Implement the graph traversal method to traverse every vertex related to a vertex and mark it as visited.

Step 4 - Use the constructed graph traversal method to determine if both vertices X and Y have been visited.

Step 5 - If both vertices X and Y are visited, return true; otherwise, return false.

method

  • Method 1 - Use DFS; it is a graph traversal algorithm that iteratively visits vertices and marks them as visited in order to study the graph.

  • Method 2 - Use the union search method, which uses data structures to monitor the division of the collection into different subgroups. It can effectively identify connected parts of undirected graphs.

method 1

In this method, it uses DFS to check if vertices X and Y are in the same connected component, we can start from vertex X and traverse the graph using DFS.

Example 1

The code is evaluated to verify whether two vertices X and Y belong to the same connected component in the graph. It employs a depth-first search (DFS) algorithm to traverse the graph and determine the connectivity of vertices. The graph is described using adjacency lists, where edges between vertices are stored as a list of each vertex's neighboring vertices. The code initializes the visited array to monitor the vertices that have been explored during the DFS traversal. Execute the DFS function on the vertex X. If the vertex Y is found to be visited during the DFS process, it means that both X and Y are part of the same connected component. The main function sets up the graph by creating an adjacency list and adding edges to it, and then performs multiple queries to verify that two vertices are in the same connected component.

#include <iostream>
#include <vector>
using namespace std;

vector<int> adjList[100005];
bool visited[100005];

void dfs(int u) {
   visited[u] = true;
   for (int v : adjList[u])
      if (!visited[v])
   dfs(v);
}

bool areVerticesInSameComponentDFS(int X, int Y, int n) {
   for (int i = 1; i <= n; i++)
      visited[i] = false;
   dfs(X);
   return visited[Y];
}

int main() {
   int n = 5;
   int m = 4;
   int edges[][2] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}};
   for (int i = 0; i < m; i++) {
      int u = edges[i][0];
      int v = edges[i][1];
      adjList[u].push_back(v);
      adjList[v].push_back(u);
   }
   int q = 2;
   int queries[][2] = {{1, 4}, {2, 5}};
   for (int i = 0; i < q; i++) {
      int X = queries[i][0];
      int Y = queries[i][1];
      if (areVerticesInSameComponentDFS(X, Y, n))
         cout << "Vertices " << X << " and " << Y << " are in the same connected component." << endl;
      else
         cout << "Vertices " << X <<" and " << Y << " are not in the same connected component." << endl;
   }
   return 0;
}

Output

Vertices 1 and 4 are in the same connected component.
Vertices 2 and 5 are in the same connected component.

Method 2

In this approach, we can first assign each vertex to a disjoint set in order to use the and find method to determine whether vertices X and Y are in the same link component. The collection of edge endpoints can then be combined for each edge in the graph. Finally, we can determine whether vertices X and Y are members of the same set, indicating that they are related components.

Example 2

This code implements and finds algorithms to check if two vertices are in the same connected component of the graph. The input is hard-coded in the form of a number of vertices n, a number of edges m, and an edge array Edges[m][2], and a query number q and a query array Queries[q][2]. The function merge(u, v) merges the set containing vertex u with the set containing vertex v. The function areVerticesInSameComponentUnionFind(X, Y) checks whether vertices X and Y are in the same connected component by finding their parent nodes and checks whether they are equal. If they are equal, the vertices are in the same connected component, otherwise they are not. The query results will be printed to the console.

#include <iostream>
using namespace std;
int parent[100005];
// Function to find the parent of a set using the Union-Find algorithm
int find(int u) {
    if (parent[u] == u) {
        return u;
    }
    return find(parent[u]);
}
void merge(int u, int v) {
    int parentU = find(u); // find the parent of u
    int parentV = find(v);
    if (parentU != parentV) {
        parent[parentU] = parentV;
    }
}
bool areVerticesInSameComponentUnionFind(int X, int Y) {
    int parentX = find(X); // find the parent of X
    int parentY = find(Y); // find the parent of Y
    return parentX == parentY;
}
int main() {
    int n = 5, m = 4;
    int edges[m][2] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}};
    for (int i = 1; i <= n; i++) {
        parent[i] = i;
    }
    for (int i = 0; i < m; i++) {
        int u = edges[i][0], v = edges[i][1];
        merge(u, v);
    }
    int q = 3;
    int queries[q][2] = {{1, 5}, {3, 5}, {1, 4}};
    for (int i = 0; i < q; i++) {
        int X = queries[i][0], Y = queries[i][1];
        if (areVerticesInSameComponentUnionFind(X, Y)) {
            cout << "Vertices " << X << " and " << Y << " are in the same connected component." << endl;
        } else {
            cout << "Vertices " << X << " and " << Y << " are not in the same connected component." << endl;
        }
    }
    return 0;
}

Output

Vertices 1 and 5 are in the same connected component.
Vertices 3 and 5 are in the same connected component.
Vertices 1 and 4 are in the same connected component.

in conclusion

In this code, we introduce two methods to determine whether two undirected graph vertices X and Y are related to each other. The second strategy employs a union-find algorithm to keep track of disjoint sets, while the first approach uses depth-first search (DFS) to traverse the graph to mark visited vertices.

The above is the detailed content of Query whether vertices X and Y are in the same connected component of an undirected graph. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C   and XML: Integrating Data in Your ProjectsC and XML: Integrating Data in Your ProjectsMay 10, 2025 am 12:18 AM

Integrating XML in a C project can be achieved through the following steps: 1) parse and generate XML files using pugixml or TinyXML library, 2) select DOM or SAX methods for parsing, 3) handle nested nodes and multi-level properties, 4) optimize performance using debugging techniques and best practices.

Using XML in C  : A Guide to Libraries and ToolsUsing XML in C : A Guide to Libraries and ToolsMay 09, 2025 am 12:16 AM

XML is used in C because it provides a convenient way to structure data, especially in configuration files, data storage and network communications. 1) Select the appropriate library, such as TinyXML, pugixml, RapidXML, and decide according to project needs. 2) Understand two ways of XML parsing and generation: DOM is suitable for frequent access and modification, and SAX is suitable for large files or streaming data. 3) When optimizing performance, TinyXML is suitable for small files, pugixml performs well in memory and speed, and RapidXML is excellent in processing large files.

C# and C  : Exploring the Different ParadigmsC# and C : Exploring the Different ParadigmsMay 08, 2025 am 12:06 AM

The main differences between C# and C are memory management, polymorphism implementation and performance optimization. 1) C# uses a garbage collector to automatically manage memory, while C needs to be managed manually. 2) C# realizes polymorphism through interfaces and virtual methods, and C uses virtual functions and pure virtual functions. 3) The performance optimization of C# depends on structure and parallel programming, while C is implemented through inline functions and multithreading.

C   XML Parsing: Techniques and Best PracticesC XML Parsing: Techniques and Best PracticesMay 07, 2025 am 12:06 AM

The DOM and SAX methods can be used to parse XML data in C. 1) DOM parsing loads XML into memory, suitable for small files, but may take up a lot of memory. 2) SAX parsing is event-driven and is suitable for large files, but cannot be accessed randomly. Choosing the right method and optimizing the code can improve efficiency.

C   in Specific Domains: Exploring Its StrongholdsC in Specific Domains: Exploring Its StrongholdsMay 06, 2025 am 12:08 AM

C is widely used in the fields of game development, embedded systems, financial transactions and scientific computing, due to its high performance and flexibility. 1) In game development, C is used for efficient graphics rendering and real-time computing. 2) In embedded systems, C's memory management and hardware control capabilities make it the first choice. 3) In the field of financial transactions, C's high performance meets the needs of real-time computing. 4) In scientific computing, C's efficient algorithm implementation and data processing capabilities are fully reflected.

Debunking the Myths: Is C   Really a Dead Language?Debunking the Myths: Is C Really a Dead Language?May 05, 2025 am 12:11 AM

C is not dead, but has flourished in many key areas: 1) game development, 2) system programming, 3) high-performance computing, 4) browsers and network applications, C is still the mainstream choice, showing its strong vitality and application scenarios.

C# vs. C  : A Comparative Analysis of Programming LanguagesC# vs. C : A Comparative Analysis of Programming LanguagesMay 04, 2025 am 12:03 AM

The main differences between C# and C are syntax, memory management and performance: 1) C# syntax is modern, supports lambda and LINQ, and C retains C features and supports templates. 2) C# automatically manages memory, C needs to be managed manually. 3) C performance is better than C#, but C# performance is also being optimized.

Building XML Applications with C  : Practical ExamplesBuilding XML Applications with C : Practical ExamplesMay 03, 2025 am 12:16 AM

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)