Find minimum moves to bring all elements in one cell of a matrix | C ++ implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Driver Code ; Coordinates of given cell ; Given Matrix ; Element to be moved ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 4 ; const int N = 5 ; void no_of_moves ( int Matrix [ M ] [ N ] , int x , int y ) { int moves = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( Matrix [ i ] [ j ] != 0 ) { moves += abs ( x - i ) ; moves += abs ( y - j ) ; } } } cout << moves << " STRNEWLINE " ; } int main ( ) { int x = 3 ; int y = 2 ; int Matrix [ M ] [ N ] = { { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 0 , 0 } } ; int num = 1 ; no_of_moves ( Matrix , x , y ) ; return 0 ; }