Question

In: Computer Science

# Problem Description Given a directed graph G = (V, E), find the number of connected...

# Problem Description

Given a directed graph G = (V, E), find the number of connected components in G.

# Input

The graph has `n` vertices and `m` edges.
There are m + 1 lines, the first line gives two numbers `n` and `m`, describing the number of vertices and edges. Each of the following lines contains two numbers `a` and `b` meaning there is an edge (a,b) belong to E. All the numbers in a line are separated by space. (`1 <= a,b <= n`)

You can assume that 2 <= n <= 10000, 1 <= m <= 50000.

Your code should read the input from standard input (e.g.
using functions `input()/raw_input()` in Python and `cin/scanf` in C++).

# Output

One number representing the number of connected components in the graph.


Your code should write the output to standard output (e.g. using functions `print` in Python and `cout/printf` in C++).

# Requirement

Your algorithm should run in O(|V| + |E|) time.

Time limtation: 5 seconds.

Memory limitation: 1.0 GB.

# Environment

Your code will be running on Ubuntu 18.04.5.

Now only accept C++ and Python2/Python3 code, g++ version 7.5.0 and Python versions are Python 2.7.17 and Python 3.6.9.

# Examples and Testing

Some examples (e.g., input-x.txt and output-x.txt, x = 1, 2) are provided.
A figure corresponding input-1 can be found in this repo too.
For Python code, try the following to test your code
```
python ./solution.py < input-x.txt > my-output-x.txt
```
For C++ code, try the following to test your code
```
g++ -o mybinary solution.cpp
./mybinary < input-x.txt > my-output-x.txt
```

Your output `my-output-x.txt` needs to be *match exactly* to the given `output-x.txt`.
On Unix-based systems you can use `diff` to compare them:
```
diff my-output-x.txt output-x.txt
```
On Windows you can use `fc` to compare them:
```
fc my-output-x.txt output-x.txt
```

# Submission

If you want to upload a single file, make sure the file is named as `solution.py` (for Python) or `solution.cpp` (for C++).
If you submit via GitHub, make sure your file is located in directory `assignment3/problem1/solution.py` (for Python) or `assignment3/problem1/solution.cpp` (for C++).

# Hints

Use adjacency list to store all the edges.

Solutions

Expert Solution

#include <bits/stdc++.h>
using namespace std;

void dfs(int currNode, int par, vector<vector<int>> &adj, vector<bool> &vis)
{
    vis[currNode] = true;
    for(int i : adj[currNode])
    {
        if(i == par || vis[i])
            continue;
        dfs(i, currNode, adj, vis);
    }
}

int main()
{
    int numNodes, numEdges;
    cin >> numNodes >> numEdges;

    vector<vector<int>> adj(numNodes + 1); // adjency list for storing graph
    for(int i = 0; i < numEdges; i++)
    {
        int x, y; 
        cin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    vector<bool> visited(numNodes + 1, 0); // for marking visited nodes
    int numComponents = 0;
    for(int i = 1; i <= numNodes; i++)
    {
        // iterating over all nodes 
        // and if node is already visited(means it already occured in some component)
        // then we'll skip else, we'll explore this component and increment the numComponennt counter.
        if(visited[i])  
            continue;
        dfs(i, 0, adj, visited);
        numComponents++;
    }

    cout << numComponents << "\n";
    return 0;
}

Create a new cpp file and name it as Solution.cpp and copy paste this code and submit it.


Related Solutions

Please use python: # Problem Description Given a directed graph G = (V, E), find the...
Please use python: # Problem Description Given a directed graph G = (V, E), find the number of connected components in G. # Input The graph has `n` vertices and `m` edges. There are m + 1 lines, the first line gives two numbers `n` and `m`, describing the number of vertices and edges. Each of the following lines contains two numbers `a` and `b` meaning there is an edge (a,b) belong to E. All the numbers in a line...
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0...
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0 for any e in E, and a source vertex s. Use Dijkstra’s algorithm to calculate distance(s,v) for all of the vertices v in V. (You can implement your own priority queue or use the build-in function for C++/Python) # Input The graph has `n` vertices and `m` edges. There are m + 1 lines, the first line gives three numbers `n`,`m` and `s`(1 <=...
A DAG is a directed graph that contains no directed cycles. Define G = (V, E)...
A DAG is a directed graph that contains no directed cycles. Define G = (V, E) in which V is the set of all nodes as {v1, v2, ..., vi , ...vn} and E is the set of edges E = {ei,j = (vi , vj ) | vi , vj ∈ V} . A topological order of a directed graph G = (V, E) is an ordering of its nodes as {v1, v2, ..., vi , ...vn} so that...
Let G = (V, E) be a directed graph, with source s ∈ V, sink t...
Let G = (V, E) be a directed graph, with source s ∈ V, sink t ∈ V, and nonnegative edge capacities {ce}. Give a polynomial-time algorithm to decide whether G has a unique minimum s-t cut (i.e., an s-t of capacity strictly less than that of all other s-t cuts).
You are given a directed graph G(V,E) with n vertices and m edges. Let S be...
You are given a directed graph G(V,E) with n vertices and m edges. Let S be the subset of vertices in G that are able to reach some cycle in G. Design an O(n + m) time algorithm to compute the set S. You can assume that G is given to you in the adjacency-list representation.
. Provide a weighted directed graph G = (V, E, c) that includes three vertices a,...
. Provide a weighted directed graph G = (V, E, c) that includes three vertices a, b, and c, and for which the maximum-cost simple path P from a to b includes vertex c, but the subpath from a to c is not the maximum-cost path from a to c
Problem 2. Consider a graph G = (V,E) where |V|=n. 2(a) What is the total number...
Problem 2. Consider a graph G = (V,E) where |V|=n. 2(a) What is the total number of possible paths of length k ≥ 0 in G from a given starting vertex s and ending vertex t? Hint: a path of length k is a sequence of k + 1 vertices without duplicates. 2(b) What is the total number of possible paths of any length in G from a given starting vertex s and ending vertex t? 2(c) What is the...
Let G = (V, E) be a directed acyclic graph modeling a communication network. Each link...
Let G = (V, E) be a directed acyclic graph modeling a communication network. Each link e in E is associated with two parameters, w(e) and d(e), where w(e) is a non-negative number representing the cost of sending a unit-sized packet through e, and d(e) is an integer between 1 and D representing the time (or delay) needed for transmitting a packet through e. Design an algorithm to find a route for sending a packet between a given pair of...
If G = (V, E) is a graph and x ∈ V , let G \...
If G = (V, E) is a graph and x ∈ V , let G \ x be the graph whose vertex set is V \ {x} and whose edges are those edges of G that don’t contain x. Show that every connected finite graph G = (V, E) with at least two vertices has at least two vertices x1, x2 ∈ V such that G \ xi is connected.
Determine, for a given graph G =V,E and a positive integer m ≤ |V |, whether...
Determine, for a given graph G =V,E and a positive integer m ≤ |V |, whether G contains a clique of size m or more. (A clique of size k in a graph is its complete subgraph of k vertices.) Determine, for a given graph G = V,E and a positive integer m ≤ |V |, whether there is a vertex cover of size m or less for G. (A vertex cover of size k for a graph G =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT