Given a binary matrix of size NxN where 1 denotes that the number i can be converted to j, and 0 denotes it cannot be converted to. Also given are two numbers X(<N)and Y(<N), the task is to find the minimum number of steps required to convert the number X to Y. If there is no such way possible, print -1.Â
Examples:Â
Input:
{{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}
X = 2, Y = 3
Output: 2
Convert 2 -> 4 -> 3, which is the minimum way possible.
Input:
{{ 0, 0, 0, 0}
{ 0, 0, 0, 1}
{ 0, 0, 0, 0}
{ 0, 1, 0, 0}}
X = 1, Y = 2
Output: -1
Approach: This problem is a variant of the Floyd-warshall algorithm where there is an edge of weight 1 between i and j i.e. mat[i][j]==1, else they don’t have an edge and we can assign edges as infinity as we do in Floyd-Warshall. Find the solution matrix and return dp[i][j] if it is not infinite. Return -1 if it is infinite which means there is no path possible between them.Â
Below is the implementation of the above approach:Â
C++
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;#define INF 99999#define size 10Â
int findMinimumSteps(int mat[size][size], int x, int y, int n){    // dist[][] will be the output matrix that    // will finally have the shortest    // distances between every pair of numbers    int dist[n][n], i, j, k;Â
    // Initially same as mat    for (i = 0; i < n; i++) {        for (j = 0; j < n; j++) {            if (mat[i][j] == 0)                dist[i][j] = INF;            else                dist[i][j] = 1;Â
            if (i == j)                dist[i][j] = 1;        }    }Â
    // Add all numbers one by one to the set    // of intermediate numbers. Before start of     // an iteration, we have shortest distances     // between all pairs of numbers such that the     // shortest distances consider only the numbers     // in set {0, 1, 2, .. k-1} as intermediate numbers.    // After the end of an iteration, vertex no. k is     // added to the set of intermediate numbers and     // the set becomes {0, 1, 2, .. k}    for (k = 0; k < n; k++) {Â
        // Pick all numbers as source one by one        for (i = 0; i < n; i++) {Â
            // Pick all numbers as destination for the            // above picked source            for (j = 0; j < n; j++) {Â
                // If number k is on the shortest path from                // i to j, then update the value of dist[i][j]                if (dist[i][k] + dist[k][j] < dist[i][j])                    dist[i][j] = dist[i][k] + dist[k][j];            }        }    }Â
    // If no path    if (dist[x][y] < INF)        return dist[x][y];    else        return -1;}Â
// Driver Codeint main(){Â
    int mat[size][size] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },                            { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },                            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } };Â
    int x = 2, y = 3;Â
    cout << findMinimumSteps(mat, x, y, size);} |
Java
// Java implementation of the above approachÂ
class GFG{         static int INF=99999;         static int findMinimumSteps(int mat[][], int x, int y, int n)    {        // dist[][] will be the output matrix that        // will finally have the shortest        // distances between every pair of numbers        int i, j, k;        int [][] dist= new int[n][n];              // Initially same as mat        for (i = 0; i < n; i++) {            for (j = 0; j < n; j++) {                if (mat[i][j] == 0)                    dist[i][j] = INF;                else                    dist[i][j] = 1;                     if (i == j)                    dist[i][j] = 1;            }        }             // Add all numbers one by one to the set        // of intermediate numbers. Before start of         // an iteration, we have shortest distances         // between all pairs of numbers such that the         // shortest distances consider only the numbers         // in set {0, 1, 2, .. k-1} as intermediate numbers.        // After the end of an iteration, vertex no. k is         // added to the set of intermediate numbers and         // the set becomes {0, 1, 2, .. k}        for (k = 0; k < n; k++) {                 // Pick all numbers as source one by one            for (i = 0; i < n; i++) {                     // Pick all numbers as destination for the                // above picked source                for (j = 0; j < n; j++) {                         // If number k is on the shortest path from                    // i to j, then update the value of dist[i][j]                    if (dist[i][k] + dist[k][j] < dist[i][j])                        dist[i][j] = dist[i][k] + dist[k][j];                }            }        }             // If no path        if (dist[x][y] < INF)            return dist[x][y];        else            return -1;    }         // Driver Code    public static void main(String []args)    {             int [][] mat = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },                        { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },                        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } };             int x = 2, y = 3;        int size=mat.length;                 System.out.println( findMinimumSteps(mat, x, y, size));    }Â
}Â
Â
// This code is contributed by ihritik |
Python3
# Python3 implementation of the above approachÂ
INF = 99999size = 10Â
def findMinimumSteps(mat, x, y, n):Â
    # dist[][] will be the output matrix     # that will finally have the shortest    # distances between every pair of numbers    dist = [[0 for i in range(n)]                for i in range(n)]    i, j, k = 0, 0, 0Â
    # Initially same as mat    for i in range(n):        for j in range(n):            if (mat[i][j] == 0):                dist[i][j] = INF            else:                dist[i][j] = 1Â
            if (i == j):                dist[i][j] = 1             # Add all numbers one by one to the set    # of intermediate numbers. Before start     # of an iteration, we have shortest distances     # between all pairs of numbers such that the     # shortest distances consider only the numbers     # in set {0, 1, 2, .. k-1} as intermediate     # numbers. After the end of an iteration, vertex     # no. k is added to the set of intermediate     # numbers and the set becomes {0, 1, 2, .. k}    for k in range(n):Â
        # Pick all numbers as source one by one        for i in range(n):Â
            # Pick all numbers as destination             # for the above picked source            for j in range(n):Â
                # If number k is on the shortest path from                # i to j, then update the value of dist[i][j]                if (dist[i][k] + dist[k][j] < dist[i][j]):                    dist[i][j] = dist[i][k] + dist[k][j]Â
    # If no path    if (dist[x][y] < INF):        return dist[x][y]    else:        return -1Â
# Driver Codemat = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],       [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],       [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]]Â
x, y = 2, 3Â
print(findMinimumSteps(mat, x, y, size))Â
# This code is contributed by Mohit kumar 29 |
C#
// C# implementation of the above approach Â
using System;class GFG {          static int INF=99999;          static int findMinimumSteps(int [,]mat, int x, int y, int n)     {         // dist[][] will be the output matrix that         // will finally have the shortest         // distances between every pair of numbers         int i, j, k;         int [,] dist= new int[n,n];              // Initially same as mat         for (i = 0; i < n; i++) {             for (j = 0; j < n; j++) {                 if (mat[i,j] == 0)                     dist[i,j] = INF;                 else                    dist[i,j] = 1;                      if (i == j)                     dist[i,j] = 1;             }         }              // Add all numbers one by one to the set         // of intermediate numbers. Before start of         // an iteration, we have shortest distances         // between all pairs of numbers such that the         // shortest distances consider only the numbers         // in set {0, 1, 2, .. k-1} as intermediate numbers.         // After the end of an iteration, vertex no. k is         // added to the set of intermediate numbers and         // the set becomes {0, 1, 2, .. k}         for (k = 0; k < n; k++) {                  // Pick all numbers as source one by one             for (i = 0; i < n; i++) {                      // Pick all numbers as destination for the                 // above picked source                 for (j = 0; j < n; j++) {                          // If number k is on the shortest path from                     // i to j, then update the value of dist[i][j]                     if (dist[i,k] + dist[k,j] < dist[i,j])                         dist[i,j] = dist[i,k] + dist[k,j];                 }             }         }              // If no path         if (dist[x,y] < INF)             return dist[x,y];         else            return -1;     }          // Driver Code     public static void Main()     {              int [,] mat = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },                         { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },                         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } };              int x = 2, y = 3;         int size = mat.GetLength(0) ;                 Console.WriteLine( findMinimumSteps(mat, x, y, size));     }     // This code is contributed by Ryuga} |
Javascript
<script>Â
// JavaScript implementation of the above approach      var INF=99999;         function findMinimumSteps(mat , x , y , n)    {        // dist will be the output matrix that        // will finally have the shortest        // distances between every pair of numbers        var i, j, k;        var dist= Array(n).fill().map(()=>Array(n).fill(0));              // Initially same as mat        for (i = 0; i < n; i++) {            for (j = 0; j < n; j++) {                if (mat[i][j] == 0)                    dist[i][j] = INF;                else                    dist[i][j] = 1;                     if (i == j)                    dist[i][j] = 1;            }        }             // Add all numbers one by one to the set        // of intermediate numbers. Before start of         // an iteration, we have shortest distances         // between all pairs of numbers such that the         // shortest distances consider only the numbers         // in set {0, 1, 2, .. k-1} as intermediate numbers.        // After the end of an iteration, vertex no. k is         // added to the set of intermediate numbers and         // the set becomes {0, 1, 2, .. k}        for (k = 0; k < n; k++) {                 // Pick all numbers as source one by one            for (i = 0; i < n; i++) {                     // Pick all numbers as destination for the                // above picked source                for (j = 0; j < n; j++) {                         // If number k is on the                     // shortest path from                    // i to j, then update the                    // value of dist[i][j]                    if (dist[i][k] + dist[k][j] < dist[i][j])                        dist[i][j] = dist[i][k] + dist[k][j];                }            }        }             // If no path        if (dist[x][y] < INF)            return dist[x][y];        else            return -1;    }         // Driver Code             var mat = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],                        [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],                        [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ] ];             var x = 2, y = 3;        var size=mat.length;                 document.write( findMinimumSteps(mat, x, y, size));Â
// This code contributed by Rajput-JiÂ
</script> |
2
Complexity Analysis:
- Time Complexity: O(N3), as we are using nested loops to traverse N3 times.
- Auxiliary Space: O(N2), as we are using extra space for the dist matrix.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
