


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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

The application of static analysis in C mainly includes discovering memory management problems, checking code logic errors, and improving code security. 1) Static analysis can identify problems such as memory leaks, double releases, and uninitialized pointers. 2) It can detect unused variables, dead code and logical contradictions. 3) Static analysis tools such as Coverity can detect buffer overflow, integer overflow and unsafe API calls to improve code security.

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.
