Open In App

Number of sink nodes in a graph

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Directed Acyclic Graph of n nodes (numbered from 1 to n) and m edges. The task is to find the number of sink nodes. A sink node is a node such that no edge emerges out of it.

Examples: 

Input : n = 4, m = 2
        Edges[] = {{2, 3}, {4, 3}} 
Output : 2

Number of sink nodes in a graph

Only node 1 and node 3 are sink nodes.

Input : n = 4, m = 2
        Edges[] = {{3, 2}, {3, 4}} 
Output : 3

The idea is to iterate through all the edges. And for each edge, mark the source node from which the edge emerged out. Now, for each node check if it is marked or not. And count the unmarked nodes. 

Algorithm: 

 
1. Make any array A[] of size equal to the
    number of nodes and initialize to 1.
2. Traverse all the edges one by one, say, 
   u -> v.
     (i) Mark A[u] as 1.
3. Now traverse whole array A[] and count 
   number of unmarked nodes.

Below is implementation of this approach:  

C++




// C++ program to count number if sink nodes
#include<bits/stdc++.h>
using namespace std;
 
// Return the number of Sink NOdes.
int countSink(int n, int m, int edgeFrom[],
                        int edgeTo[])
{
    // Array for marking the non-sink node.
    int mark[n];
    memset(mark, 0, sizeof mark);
 
    // Marking the non-sink node.
    for (int i = 0; i < m; i++)
        mark[edgeFrom[i]] = 1;
 
    // Counting the sink nodes.
    int count = 0;
    for (int i = 1; i <= n ; i++)
        if (!mark[i])
            count++;
 
    return count;
}
 
// Driven Program
int main()
{
    int n = 4, m = 2;
    int edgeFrom[] = { 2, 4 };
    int edgeTo[] = { 3, 3 };
 
    cout << countSink(n, m, edgeFrom, edgeTo) << endl;
 
    return 0;
}


Java




// Java program to count number if sink nodes
import java.util.*;
 
class GFG
{
 
// Return the number of Sink NOdes.
static int countSink(int n, int m,
                     int edgeFrom[], int edgeTo[])
{
    // Array for marking the non-sink node.
    int []mark = new int[n + 1];
 
    // Marking the non-sink node.
    for (int i = 0; i < m; i++)
        mark[edgeFrom[i]] = 1;
 
    // Counting the sink nodes.
    int count = 0;
    for (int i = 1; i <= n ; i++)
        if (mark[i] == 0)
            count++;
 
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 4, m = 2;
    int edgeFrom[] = { 2, 4 };
    int edgeTo[] = { 3, 3 };
 
    System.out.println(countSink(n, m,
                       edgeFrom, edgeTo));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to count number if sink nodes
 
# Return the number of Sink NOdes.
def countSink(n, m, edgeFrom, edgeTo):
     
    # Array for marking the non-sink node.
    mark = [0] * (n + 1)
 
    # Marking the non-sink node.
    for i in range(m):
        mark[edgeFrom[i]] = 1
 
    # Counting the sink nodes.
    count = 0
    for i in range(1, n + 1):
        if (not mark[i]):
            count += 1
 
    return count
 
# Driver Code
if __name__ == '__main__':
     
    n = 4
    m = 2
    edgeFrom = [2, 4]
    edgeTo = [3, 3]
 
    print(countSink(n, m, edgeFrom, edgeTo))
 
# This code is contributed by PranchalK


C#




// C# program to count number if sink nodes
using System;
     
class GFG
{
 
// Return the number of Sink NOdes.
static int countSink(int n, int m,
                     int []edgeFrom,
                     int []edgeTo)
{
    // Array for marking the non-sink node.
    int []mark = new int[n + 1];
 
    // Marking the non-sink node.
    for (int i = 0; i < m; i++)
        mark[edgeFrom[i]] = 1;
 
    // Counting the sink nodes.
    int count = 0;
    for (int i = 1; i <= n ; i++)
        if (mark[i] == 0)
            count++;
 
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 4, m = 2;
    int []edgeFrom = { 2, 4 };
    int []edgeTo = { 3, 3 };
 
    Console.WriteLine(countSink(n, m,
                      edgeFrom, edgeTo));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript program to count number if sink nodes
 
// Return the number of Sink NOdes.
function countSink(n, m, edgeFrom, edgeTo)
{
     
    // Array for marking the non-sink node.
    let mark = new Array(n + 1);
    for(let i = 0; i < n + 1; i++)
    {
        mark[i] = 0;
    }
     
    // Marking the non-sink node.
    for(let i = 0; i < m; i++)
        mark[edgeFrom[i]] = 1;
   
    // Counting the sink nodes.
    let count = 0;
    for(let i = 1; i <= n; i++)
        if (mark[i] == 0)
            count++;
   
    return count;
}
 
// Driver Code
let n = 4, m = 2;
let edgeFrom = [ 2, 4 ];
let edgeTo = [ 3, 3 ];
 
document.write(countSink(n, m,
                         edgeFrom, edgeTo));
 
// This code is contributed by rag2127
 
</script>


Output: 

2

Time Complexity: O(m + n) where n is number of nodes and m is number of edges.

Space complexity : O(n) because it uses an array of size n to store the non-sink nodes.

Related Article: 
The Celebrity Problem

 



Previous Article
Next Article

Similar Reads

Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Determine whether a universal sink exists in a directed graph
Determine whether a universal sink exists in a directed graph. A universal sink is a vertex which has no edge emanating from it, and all other vertices have an edge towards the sink. Input : v1 -&gt; v2 (implies vertex 1 is connected to vertex 2) v3 -&gt; v2 v4 -&gt; v2 v5 -&gt; v2 v6 -&gt; v2 Output : Sink found at vertex 2 Input : v1 -&gt; v6 v2
13 min read
Sink even nodes in Binary Tree
Given a Binary Tree having odd and even elements, sink all its even valued nodes such that no node with an even value could be a parent of a node with an odd value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node with odd nodes and all even nodes follow the rule
13 min read
Sink Odd nodes in Binary Tree
Given a Binary Tree having odd and even elements, sink all its odd valued nodes such that no node with odd value could be parent of node with even value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node with even nodes and all odd nodes follows the rule) Input :
13 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Maximize count of nodes disconnected from all other nodes in a Graph
Given two integers N and E which denotes the number of nodes and the number of edges of an undirected graph, the task is to maximize the number of nodes which is not connected to any other node in the graph, without using any self-loops. Examples: Input: N = 5, E = 1 Output: 3 Explanation: Since there is only 1 edge in the graph which can be used t
4 min read
Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, retu
10 min read
Count of nodes accessible from all other nodes of Graph
Given a directed graph with N nodes and M edges in array V[], the task is to find the number of nodes that are accessible from all other nodes i.e., they have at least one path from all other nodes. Examples: Input: N = 5 and M = 5, V = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]Output: 2Explanation:We can look closely after forming graph than captain
15 min read
Print levels with odd number of nodes and even number of nodes
Given an N-ary tree, print all the levels with odd and even numbers of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2Note: The level numbers starts from 1. That is, the r
15+ min read
Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
Given a number N which is the number of nodes in a graph, the task is to find the maximum number of edges that N-vertex graph can have such that graph is triangle-free (which means there should not be any three edges A, B, C in the graph such that A is connected to B, B is connected to C and C is connected to A). The graph cannot contain a self-loo
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg