- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find minimum steps required to reach the end of a matrix in C++

Suppose we have a 2D matrix with positive integers. We have to find the minimum steps required to move from to the end of the matrix (rightmost bottom cell), If we are at cell (i, j), we can go to the cell (i, j+mat[i, j]) or (i+mat[i, j], j), We cannot cross the bounds. So if the matrix is like −

2 | 1 | 2 |

1 | 1 | 1 |

1 | 1 | 1 |

The output will be 2. Path will be (0, 0) →(0, 2) → (2, 2)

Here we will use the Dynamic programming approach to solve this. Suppose we are at cell (i, j), we want to reach (n-1, n-1) cell. We can use the recurrence relation like below −

*DP[i, j]=1+min (DP [i+arr [i , j] , j], DP[i , j+arr [ i , j]])*

## Example

#include<iostream> #define N 3 using namespace std; int table[N][N]; bool temp_val[N][N]; int countSteps(int i, int j, int arr[][N]) { if (i == N - 1 and j == N - 1) return 0; if (i > N - 1 || j > N - 1) return INT_MAX; if (temp_val[i][j]) return table[i][j]; temp_val[i][j] = true; table[i][j] = 1 + min(countSteps(i + arr[i][j], j, arr), countSteps(i, j + arr[i][j], arr)); return table[i][j]; } int main() { int arr[N][N] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = countSteps(0, 0, arr); if (ans >= INT_MAX) cout << -1; else cout <<"Number of steps: "<< ans; }

## Output

Number of steps: 2

- Related Questions & Answers
- Program to find minimum number of hops required to reach end position in Python
- How to find the minimum number of jumps required to reach the end of the array using C#?
- Find the minimum number of steps to reach M from N in C++
- Program to find number of minimum steps to reach last index in Python
- Program to find minimum number of steps required to catch the opponent in C++
- Maximum power of jump required to reach the end of string in C++
- Program to find minimum number of buses required to reach final target in python
- C Program for Minimum number of jumps to reach the end
- How to find the minimum number of steps needed by knight to reach the destination using C#?
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to Find Minimum Jumps Required to Reach a Value with Different Parity in Python
- C++ program to find minimum number of steps needed to move from start to end
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Program to find number of minimum steps required to meet all person at any cell in Python

Advertisements