Given a directed graph having n nodes. For each node, delete all the outgoing edges except the outgoing edge with minimum weight. Apply this deletion operation for every node and then print the final graph remaining where each node of the graph has at most one outgoing edge and that too with minimum weight.
Note: Here, the graph is stored as Adjacency Matrix for ease.
Examples :
Input : Adjacency Matrix of input graph : | 1 2 3 4 --------------- 1 | 0 3 2 5 2 | 0 2 4 7 3 | 1 2 0 3 4 | 5 2 1 3 Output : Adjacency Matrix of output graph : | 1 2 3 4 --------------- 1 | 0 0 2 0 2 | 0 2 0 0 3 | 1 0 0 0 4 | 0 0 1 0
For every row of the adjacency matrix of the graph keep the minimum element (except zero) and make the rest of all zero. Do this for every row of the input matrix. Finally, print the resultant Matrix.
Example :
C++
// CPP program for minimizing graph#include <bits/stdc++.h>Â
using namespace std;Â
// Utility function for// finding min of a rowint minFn(int arr[]){Â Â Â Â int min = INT_MAX;Â
    for (int i = 0; i < 4; i++)        if (min > arr[i])            min = arr[i];    return min;}Â
// Utility function for minimizing graphvoid minimizeGraph(int arr[][4]){Â Â Â Â int min;Â
    // Set empty edges to INT_MAX    for (int i = 0; i < 4; i++)        for (int j = 0; j < 4; j++)            if (arr[i][j] == 0)                arr[i][j] = INT_MAX;Â
    // Finding minimum of each row    // and deleting rest of edges    for (int i = 0; i < 4; i++) {Â
        // Find minimum element of row        min = minFn(arr[i]);Â
        for (int j = 0; j < 4; j++) {            // If edge value is not min            // set it to zero, also            // edge value INT_MAX denotes that            // initially edge value was zero            if (!(arr[i][j] == min) || (arr[i][j] == INT_MAX))                arr[i][j] = 0;            else                min = 0;        }    }Â
    // Print result;    for (int i = 0; i < 4; i++) {        for (int j = 0; j < 4; j++)            cout << arr[i][j] << " ";        cout << "\n";    }}Â
// Driver Programint main(){    // Input Graph    int arr[4][4] = { 1, 2, 4, 0,                      0, 0, 0, 5,                      0, 2, 0, 3,                      0, 0, 0, 0 };Â
    minimizeGraph(arr);Â
    return 0;} |
Java
// Java program for// minimizing graphimport java.io.*;import java.util.*;import java.lang.*;Â
class GFG {Â
    // Utility function for    // finding min of a row    static int minFn(int arr[])    {        int min = Integer.MAX_VALUE;Â
        for (int i = 0;             i < arr.length; i++)            if (min > arr[i])                min = arr[i];        return min;    }Â
    // Utility function    // for minimizing graph    static void minimizeGraph(int arr[][])    {        int min;Â
        // Set empty edges        // to INT_MAX        for (int i = 0;             i < arr.length; i++)            for (int j = 0;                 j < arr.length; j++)                if (arr[i][j] == 0)                    arr[i][j] = Integer.MAX_VALUE;Â
        // Finding minimum of each        // row and deleting rest        // of edges        for (int i = 0;             i < arr.length; i++) {Â
            // Find minimum            // element of row            min = minFn(arr[i]);Â
            for (int j = 0;                 j < arr.length; j++) {                // If edge value is not                // min set it to zero,                // also edge value INT_MAX                // denotes that initially                // edge value was zero                if ((arr[i][j] != min) || (arr[i][j] == Integer.MAX_VALUE))                    arr[i][j] = 0;                else                    min = 0;            }        }Â
        // Print result;        for (int i = 0;             i < arr.length; i++) {            for (int j = 0;                 j < arr.length; j++)                System.out.print(arr[i][j] + " ");            System.out.print("\n");        }    }Â
    // Driver Code    public static void main(String[] args)    {        // Input Graph        int arr[][] = { { 1, 2, 4, 0 },                        { 0, 0, 0, 5 },                        { 0, 2, 0, 3 },                        { 0, 0, 0, 0 } };Â
        minimizeGraph(arr);    }} |
Python3
# Python3 program for minimizing graph Â
# Utility function for finding min of a row def minFn(arr): Â
    minimum = float('inf')          for i in range(0, len(arr)):         if minimum > arr[i]:             minimum = arr[i]     return minimumÂ
# Utility function for minimizing graph def minimizeGraph(arr): Â
    # Set empty edges to INT_MAX     n=len(arr)    for i in range(0, n):         for j in range(0, n):             if arr[i][j] == 0:                 arr[i][j] = float('inf') Â
    # Finding minimum of each row     # and deleting rest of edges     for i in range(0, n):                  # Find minimum element of row         minimum = minFn(arr[i])                  for j in range(0, n):                         # If edge value is not min             # set it to zero, also             # edge value INT_MAX denotes that             # initially edge value was zero             if ((not(arr[i][j] == minimum)) or                    (arr[i][j] == float('inf'))):                 arr[i][j] = 0            else:                minimum = 0             # Print result     for i in range(0, n):         for j in range(0, n):             print(arr[i][j], end = " ")         print() Â
# Driver Code if __name__ == "__main__":          # Input Graph     arr = [[1, 2, 4, 0],            [0, 0, 0, 5],            [0, 2, 0, 3],            [0, 0, 0, 0]]          minimizeGraph(arr)      # This code is contributed by # Rituraj Jain |
C#
// C# program for// minimizing graphusing System;Â
class GFG {Â
    // Utility function for    // finding min of a row    static int minFn(int[] arr)    {        int min = int.MaxValue;Â
        for (int i = 0;             i < arr.Length; i++)            if (min > arr[i])                min = arr[i];        return min;    }Â
    // Utility function    // for minimizing graph    static void minimizeGraph(int[, ] arr)    {        int min;Â
        // Set empty edges        // to INT_MAX        for (int i = 0;             i < arr.GetLength(0); i++)            for (int j = 0;                 j < arr.GetLength(1); j++)                if (arr[i, j] == 0)                    arr[i, j] = int.MaxValue;Â
        // Finding minimum of each        // row and deleting rest        // of edges        for (int i = 0; i < arr.GetLength(0); i++) {Â
            // Find minimum            // element of row            min = minFn(GetRow(arr, i));Â
            for (int j = 0;                 j < arr.GetLength(1); j++) {                // If edge value is not                // min set it to zero,                // also edge value INT_MAX                // denotes that initially                // edge value was zero                if ((arr[i, j] != min) || (arr[i, j] == int.MaxValue))                    arr[i, j] = 0;                else                    min = 0;            }        }Â
        // Print result;        for (int i = 0;             i < arr.GetLength(0); i++) {            for (int j = 0;                 j < arr.GetLength(1); j++)                Console.Write(arr[i, j] + " ");            Console.Write("\n");        }    }Â
    public static int[] GetRow(int[, ] matrix, int row)    {        var rowLength = matrix.GetLength(1);        var rowVector = new int[rowLength];Â
        for (var i = 0; i < rowLength; i++)            rowVector[i] = matrix[row, i];Â
        return rowVector;    }Â
    // Driver Code    public static void Main(String[] args)    {        // Input Graph        int[, ] arr = { { 1, 2, 4, 0 },                        { 0, 0, 0, 5 },                        { 0, 2, 0, 3 },                        { 0, 0, 0, 0 } };Â
        minimizeGraph(arr);    }}Â
// This code contributed by Rajput-Ji |
PHP
<?php// PHP program for minimizing graphÂ
// Utility function for finding // min of a row function minFn($arr) { Â Â Â Â $min = PHP_INT_MAX; Â Â Â Â Â Â Â Â Â for ($i = 0; $i < 4; $i++) Â Â Â Â Â Â Â Â if ($min > $arr[$i]) Â Â Â Â Â Â Â Â Â Â Â Â $min = $arr[$i]; Â Â Â Â return $min; } Â
// Utility function for minimizing graph function minimizeGraph($arr) { Â Â Â Â $min; Â Â Â Â Â Â Â Â Â // Set empty edges to INT_MAX Â Â Â Â for ($i = 0; $i < 4; $i++) Â Â Â Â Â Â Â Â for ($j = 0; $j < 4; $j++) Â Â Â Â Â Â Â Â Â Â Â Â if ($arr[$i][$j] == 0) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $arr[$i][$j] = PHP_INT_MAX; Â
    // Finding minimum of each row     // and deleting rest of edges     for ($i = 0; $i < 4; $i++)    {                  // Find minimum element of row         $min = minFn($arr[$i]);                  for ($j = 0; $j < 4; $j++)         {             // If edge value is not min             // set it to zero, also             // edge value INT_MAX denotes that             // initially edge value was zero             if (!($arr[$i][$j] == $min) ||                  ($arr[$i][$j] == PHP_INT_MAX))                 $arr[$i][$j] = 0;             else                $min = 0;         }     }          // Print result;     for ($i = 0; $i < 4; $i++)    {         for ($j = 0; $j < 4; $j++)             echo $arr[$i][$j], " ";         echo "\n";     } } Â
// Driver CodeÂ
// Input Graph $arr = array(array(1, 2, 4, 0), Â Â Â Â Â Â Â Â Â Â Â Â Â array(0, 0, 0, 5), Â Â Â Â Â Â Â Â Â Â Â Â Â array(0, 2, 0, 3), Â Â Â Â Â Â Â Â Â Â Â Â Â array(0, 0, 0, 0)); Â
minimizeGraph($arr); Â
// This code is contributed by ajit.?> |
Javascript
<script>Â
// Javascript program for minimizing graphÂ
// Utility function for// finding min of a rowfunction minFn(arr){Â Â Â Â var min = 1000000000;Â
    for (var i = 0; i < 4; i++)        if (min > arr[i])            min = arr[i];    return min;}Â
// Utility function for minimizing graphfunction minimizeGraph(arr){Â Â Â Â var min;Â
    // Set empty edges to INT_MAX    for (var i = 0; i < 4; i++)        for (var j = 0; j < 4; j++)            if (arr[i][j] == 0)                arr[i][j] = 1000000000;Â
    // Finding minimum of each row    // and deleting rest of edges    for (var i = 0; i < 4; i++) {Â
        // Find minimum element of row        min = minFn(arr[i]);Â
        for (var j = 0; j < 4; j++) {            // If edge value is not min            // set it to zero, also            // edge value INT_MAX denotes that            // initially edge value was zero            if (!(arr[i][j] == min) || (arr[i][j] == 1000000000))                arr[i][j] = 0;            else                min = 0;        }    }Â
    // Print result;    for (var i = 0; i < 4; i++) {        for (var j = 0; j < 4; j++)            document.write( arr[i][j] + " ");        document.write( "<br>");    }}Â
// Driver Program// Input Graphvar arr = [ [1, 2, 4, 0],                  [0, 0, 0, 5],                  [0, 2, 0, 3],                  [0, 0, 0, 0 ]];minimizeGraph(arr);Â
// This code is contributed by noob2000.</script> |
1 0 0 0 0 0 0 5 0 2 0 0 0 0 0 0
Time Complexity: O(n^2)Â
Auxiliary Space: O(1) as it is using constant space for variables, and space for input adjacency matrix is not considered
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More here on that Topic: geeksforgeeks.org/remove-all-outgoing-edges-except-edge-with-minimum-weight/ […]
… [Trackback]
[…] Find More to that Topic: geeksforgeeks.org/remove-all-outgoing-edges-except-edge-with-minimum-weight/ […]
… [Trackback]
[…] Find More on to that Topic: geeksforgeeks.org/remove-all-outgoing-edges-except-edge-with-minimum-weight/ […]
… [Trackback]
[…] Read More on to that Topic: geeksforgeeks.org/remove-all-outgoing-edges-except-edge-with-minimum-weight/ […]