
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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
Advertisements