Given a 2D matrix consisting of positive integers, the task is to find the minimum number of steps required to reach the end(leftmost-bottom cell) of the matrix. If we are at cell (i, j) we can go to cells (i, j+arr[i][j]) or (i+arr[i][j], j). We can not go out of bounds. If no path exists, print -1.
Examples:
Input : 
mat[][] = {{2, 1, 2},
           {1, 1, 1},
           {1, 1, 1}}
Output : 2
Explanation : The path will be {0, 0} -> {0, 2} -> {2, 2}
Thus, we are reaching end in two steps.
Input :
mat[][] = {{1, 1, 2},
           {1, 1, 1},
           {2, 1, 1}}
Output : 3
A simple solution is to explore all possible solutions. This will take exponential time.
Better approach: We can use dynamic programming to solve this problem in polynomial time.
Let’s decide the states of ‘dp’. We will build up our solution on 2d DP. 
Let’s say we are at cell {i, j}. We will try to find the minimum number of steps required to reach the cell (n-1, n-1) from this cell. 
We only have two possible paths i.e. to cells {i, j+arr[i][j]} or {i+arr[i][j], j}.
A simple recurrence relation will be: 
dp[i][j] = 1 + min(dp[i+arr[i][j]][j], dp[i][j+arr[i][j]])
Below is the implementation of the above idea:
C++
| // C++ program to implement above approach#include <bits/stdc++.h>#define n 3usingnamespacestd;// 2d array to store// states of dpintdp[n][n];// array to determine whether// a state has been solved beforeintv[n][n];// Function to find the minimum number of// steps to reach the end of matrixintminSteps(inti, intj, intarr[][n]){    // base cases    if(i == n - 1 and j == n - 1)        return0;    if(i > n - 1 || j > n - 1)        return9999999;    // if a state has been solved before    // it won't be evaluated again.    if(v[i][j])        returndp[i][j];    v[i][j] = 1;    // recurrence relation    dp[i][j] = 1 + min(minSteps(i + arr[i][j], j, arr),                       minSteps(i, j + arr[i][j], arr));    returndp[i][j];}// Driver Codeintmain(){    intarr[n][n] = { { 2, 1, 2 },                      { 1, 1, 1 },                      { 1, 1, 1 } };    intans = minSteps(0, 0, arr);    if(ans >= 9999999)        cout << -1;    else        cout << ans;    return0;} | 
Java
| // Java program to implement above approachclassGFG {    staticintn = 3;    // 2d array to store    // states of dp    staticintdp[][] = newint[n][n];    // array to determine whether    // a state has been solved before    staticint[][] v = newint[n][n];    // Function to find the minimum number of    // steps to reach the end of matrix    staticintminSteps(inti, intj, intarr[][])    {        // base cases        if(i == n - 1&& j == n - 1) {            return0;        }        if(i > n - 1|| j > n - 1) {            return9999999;        }        // if a state has been solved before        // it won't be evaluated again.        if(v[i][j] == 1) {            returndp[i][j];        }        v[i][j] = 1;        // recurrence relation        dp[i][j] = 1+ Math.min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr));        returndp[i][j];    }    // Driver Code    publicstaticvoidmain(String[] args)    {        intarr[][] = { { 2, 1, 2},                        { 1, 1, 1},                        { 1, 1, 1} };        intans = minSteps(0, 0, arr);        if(ans >= 9999999) {            System.out.println(-1);        }        else{            System.out.println(ans);        }    }}// This code contributed by Rajput-Ji | 
Python3
| # Python3 program to implement above approach importnumpy as np;n =3# 2d array to store # states of dp dp =np.zeros((n, n)); # array to determine whether # a state has been solved before v =np.zeros((n, n)); # Function to find the minimum number of # steps to reach the end of matrix defminSteps(i, j, arr) :     # base cases     if(i ==n -1andj ==n -1) :        return0;     if(i > n -1orj > n -1) :        return9999999;     # if a state has been solved before     # it won't be evaluated again.     if(v[i][j]) :        returndp[i][j];     v[i][j] =1;     # recurrence relation     dp[i][j] =1+min(minSteps(i +arr[i][j], j, arr),                     minSteps(i, j +arr[i][j], arr));     returndp[i][j]; # Driver Code arr =[ [ 2, 1, 2],             [ 1, 1, 1],             [ 1, 1, 1]            ];            ans =minSteps(0, 0, arr); if(ans >=9999999) :    print(-1);         else:    print(ans); # This code is contributed by AnkitRai01 | 
C#
| // C# program to implement above approachusingSystem;classGFG{        staticintn = 3;    // 2d array to store    // states of dp    staticint[,]dp = newint[n, n];    // array to determine whether    // a state has been solved before    staticint[,] v = newint[n, n];    // Function to find the minimum number of    // steps to reach the end of matrix    staticintminSteps(inti, intj, int[,]arr)    {        // base cases        if(i == n - 1 && j == n - 1)         {            return0;        }        if(i > n - 1 || j > n - 1)         {            return9999999;        }        // if a state has been solved before        // it won't be evaluated again.        if(v[i, j] == 1)         {            returndp[i, j];        }        v[i, j] = 1;        // recurrence relation        dp[i, j] = 1 + Math.Min(minSteps(i + arr[i,j], j, arr),                            minSteps(i, j + arr[i,j], arr));        returndp[i, j];    }    // Driver Code    staticpublicvoidMain ()    {        int[,]arr = { { 2, 1, 2 },                        { 1, 1, 1 },                        { 1, 1, 1 } };        intans = minSteps(0, 0, arr);        if(ans >= 9999999)         {            Console.WriteLine(-1);        }        else        {            Console.WriteLine(ans);        }    }}// This code contributed by ajit. | 
Javascript
| <script>    // Javascript program to implement    // above approach        let n = 3;      // 2d array to store    // states of dp    let dp = newArray(n);    for(let i = 0; i < n; i++)    {        dp[i] = newArray(n);    }      // array to determine whether    // a state has been solved before    let v = newArray(n);    for(let i = 0; i < n; i++)    {        v[i] = newArray(n);    }      // Function to find the minimum number of    // steps to reach the end of matrix    functionminSteps(i, j, arr)    {        // base cases        if(i == n - 1 && j == n - 1)         {            return0;        }          if(i > n - 1 || j > n - 1)         {            return9999999;        }          // if a state has been solved before        // it won't be evaluated again.        if(v[i][j] == 1) {            returndp[i][j];        }          v[i][j] = 1;          // recurrence relation        dp[i][j] = 1 + Math.min(minSteps(i +         arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr));          returndp[i][j];    }        let arr = [ [ 2, 1, 2 ],               [ 1, 1, 1 ],               [ 1, 1, 1 ] ];      let ans = minSteps(0, 0, arr);    if(ans >= 9999999) {      document.write(-1);    }    else{      document.write(ans);    }    </script> | 
2
Time Complexity: O(N2).
Auxiliary Space: O(N2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







