Minimum path need to reverse to reach each node in a tree from each vertex
Given a directed tree consisting of N nodes valued from [0, N – 1] and M edges, the task is to find the minimum number of edges that need to reverse for each node X such that there is a path from node X to each vertex of the given Tree.
Examples:
Input: N = 6, edges[][] = {{0, 1}, {1, 3}, {2, 3}, {4, 0}, {4, 5}}
Output: 2 2 2 3 1 2
Explanation:
The answer for node 0 is 2, which can be calculated as:
From 0 to 0: No edges are required to reverse to reach 0 from 0.
From 0 to 1: Can be reached directly using edge 0 -> 1.
From 0 to 2: The edge 2 -> 3 must be reversed for the path 0 -> 1 -> 3 -> 2 to reach 2 from node 0.
From 0 to 3: Can be reached directly as 0 -> 1 -> 3.
From 0 to 4: The edge 4 -> 0 must be reversed to reach 4 from node 0.
From 0 to 5: The edge 4 -> 0 must be reversed to reach 5 from node 0 as 0 -> 4 -> 5
To reach every node from the node 0, edge 2 -> 3 and edge 4 -> 0 is reversed. So, a total of 2 edges is reversed for node 0. Similarly, the ans for all the nodes can be calculated.
Input: N = 5, edges[][] = {{1, 0}, {1, 2}, {3, 2}, {3, 4}}
Output: 2 1 2 1 2
Approach: To solve the above problem, the idea is to store the directed edge in the adjacency list along with the reversed directed edge with the negative sign i.e. for directed edge a -> b store the edge a -> b and b -> -a. Then, for each node X of the tree, the answer can be calculated as the number of negative edges encountered in the simple Depth For Search(DFS) from that node X.Follow the steps below to solve the problem:
- Initialize a 2-dimensional vector, say graph[][], to store the edges of the graph.
- Traverse the array edges[][] and for each pair (a, b), push the directed edge b in graph[a] and reversed directed edge -a in graph[b].
- Iterate over the range N, and for each node:
- Initialize a variable, say count = 0, to count the required number of edges to reverse.
- Call a recursive function, say reorderPaths(node, graph, count, visited) to perform the DFS on the tree.
- Increase the value of count for each of the negative edges traversed in the DFS.
- Print the value of the count, for each iteration of the node.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void reorderPaths(
int s, vector<vector< int > > graph,
int & count, vector< bool >& visited)
{
visited[s] = true ;
for ( auto i : graph[s]) {
if (!visited[ abs (i)]) {
if (i < 0)
count++;
reorderPaths( abs (i), graph,
count, visited);
}
}
}
void minReorder( int n, vector<vector< int > > edges)
{
vector<vector< int > > graph(n);
for ( int i = 0; i < edges.size(); i++) {
int a = edges[i][0];
int b = edges[i][1];
graph[a].push_back(b);
graph[b].push_back(-a);
}
for ( int i = 0; i < n; i++) {
vector< bool > visited(n, false );
int count = 0;
reorderPaths(i, graph, count, visited);
cout << count << " " ;
}
}
int main()
{
int N = 6;
vector<vector< int > > edges
= { { 0, 1 }, { 1, 3 }, { 2, 3 }, { 4, 0 }, { 4, 5 } };
minReorder(N, edges);
return 0;
}
|
Java
import java.util.*;
public class GFG{
static int count;
static void reorderPaths(
int s, Vector<Integer>[] graph, boolean [] visited)
{
visited[s] = true ;
for ( int i : graph[s]) {
if (!visited[(Math.abs(i))]) {
if (i < 0 )
count++;
reorderPaths(Math.abs(i), graph, visited);
}
}
}
static void minReorder( int n, int [][] edges)
{
Vector<Integer>[] graph = new Vector[n];
for ( int i = 0 ; i < n; i++)
graph[i] = new Vector<>();
for ( int i = 0 ; i < edges.length; i++) {
int a = edges[i][ 0 ];
int b = edges[i][ 1 ];
graph[a].add(b);
graph[b].add(-a);
}
for ( int i = 0 ; i < n; i++) {
boolean []visited = new boolean [n];
count = 0 ;
reorderPaths(i, graph, visited);
System.out.print(count+ " " );
}
}
public static void main(String[] args)
{
int N = 6 ;
int [][] edges
= { { 0 , 1 }, { 1 , 3 }, { 2 , 3 }, { 4 , 0 }, { 4 , 5 } };
minReorder(N, edges);
}
}
|
Python3
count = 0
visited = []
def reorderPaths(s, graph):
global count
visited[s] = True
for i in graph[s]:
if (visited[ abs (i)] = = False ):
if (i < 0 ):
count + = 1
reorderPaths( abs (i), graph)
def minReorder(n, edges):
global count
global visited
graph = [[] for i in range (n)]
for i in range ( len (edges)):
a = edges[i][ 0 ]
b = edges[i][ 1 ]
graph[a].append(b)
graph[b].append( - a)
for i in range (n):
visited = [ False for i in range (n)]
count = 0
reorderPaths(i, graph)
print (count,end = " " )
if __name__ = = '__main__' :
N = 6
edges = [[ 0 , 1 ],[ 1 , 3 ],[ 2 , 3 ],[ 4 , 0 ],[ 4 , 5 ]]
minReorder(N, edges)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int count;
static void ReorderPaths( int s, List< int >[] graph,
bool [] visited)
{
visited[s] = true ;
foreach ( int i in graph[s])
{
if (!visited[(Math.Abs(i))]) {
if (i < 0)
count++;
ReorderPaths(Math.Abs(i), graph, visited);
}
}
}
static void MinReorder( int n, int [][] edges)
{
List< int >[] graph = new List< int >[ n ];
for ( int i = 0; i < n; i++)
graph[i] = new List< int >();
for ( int i = 0; i < edges.Length; i++) {
int a = edges[i][0];
int b = edges[i][1];
graph[a].Add(b);
graph[b].Add(-a);
}
for ( int i = 0; i < n; i++) {
bool [] visited = new bool [n];
count = 0;
ReorderPaths(i, graph, visited);
Console.Write(count + " " );
}
}
public static void Main( string [] args)
{
int N = 6;
int [][] edges
= { new int [] { 0, 1 }, new int [] { 1, 3 },
new int [] { 2, 3 }, new int [] { 4, 0 },
new int [] { 4, 5 } };
MinReorder(N, edges);
}
}
|
Javascript
<script>
let graph;
let edges;
let count;
let visited;
function reorderPaths(s)
{
visited[s] = true ;
for (let i = 0; i < graph[s].length; i++) {
if (!visited[(Math.abs(graph[s][i]))]) {
if (graph[s][i] < 0)
count++;
reorderPaths(Math.abs(graph[s][i]));
}
}
}
function minReorder(n)
{
graph = [];
for (let i = 0; i < n; i++)
{
graph.push([]);
}
for (let i = 0; i < edges.length; i++) {
let a = edges[i][0];
let b = edges[i][1];
graph[a].push(b);
graph[b].push(-a);
}
for (let i = 0; i < n; i++) {
visited = new Array(n);
visited.fill( false );
count = 0;
reorderPaths(i);
document.write(count + " " );
}
}
let N = 6;
edges = [ [ 0, 1 ], [ 1, 3 ], [ 2, 3 ], [ 4, 0 ], [ 4, 5 ] ];
minReorder(N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...