Minimize steps required to move all 1 's in a matrix to a given index | Java 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
import java . util . * ; class GFG { static int findAns ( 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 += Math . abs ( x - i ) + Math . abs ( y - j ) ; } } } return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 } } ; int x = 0 , y = 2 ; System . out . print ( findAns ( mat , x , y , mat . length , mat [ 0 ] . length ) + "NEW_LINE"); } }