Minimize steps required to move all 1 's in a matrix to a given index | C ++ program to calculate the minimum steps required to reach a given cell from all cells consisting of 1 's ; Function to calculate and return the minimum number of steps required to move all 1 s to ( X , Y ) ; Iterate the given matrix ; Update the answer with minimum moves required for the given element to reach the given index ; Return the number of steps ; Driver Code ; Given matrix ; Given position ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findAns ( vector < vector < int > > mat , int x , int y , int n , int m ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { ans += abs ( x - i ) + abs ( y - j ) ; } } } return ans ; } int main ( ) { vector < vector < int > > mat = { { 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 } } ; int x = 0 , y = 2 ; cout << findAns ( mat , x , y , mat . size ( ) , mat [ 0 ] . size ( ) ) << endl ; return 0 ; }