Skip to content
Related Articles
Open in App
Not now

Related Articles

Minimize steps required to move all 1’s in a matrix to a given index

Improve Article
Save Article
  • Last Updated : 30 Aug, 2022
Improve Article
Save Article

Given a binary matrix mat[][] of size NxM and two integers X and Y, the task is to find the minimum number steps required to move all 1’s in the given matrix to the cell (X, Y), where, one step involves moving a cell left, right, up or down.
Examples: 
 

Input: mat[][] = { {1, 0, 1}, {0, 1, 0}, {1, 0, 1} }, X = 1, Y = 1 
Output:
Explanation: 
Cells (0, 0), (0, 2), (1, 1), (2, 0) and (2, 2) consists of 1. 
Moving 1 at index (0, 0) to (1, 1) requires 2 steps 
(0, 0) -> (0, 1) ->(1, 0) 
Moving 1 at index (0, 2) to (1, 1) requires 2 steps 
Moving 1 at index (2, 0) to (1, 1) requires 2 steps 
Moving 1 at index (2, 2) to (1, 1) requires 2 steps 
Therefore, 8 steps are required.
Input: mat[][] = { {1, 0, 0, 0}, {0, 1, 0, 1}, {1, 0, 1, 1} }, X = 0, Y = 2 
Output: 15 
 

Approach: 
The idea is to traverse the given matrix and find the cells consisting of 1. For any cell (i, j) consisting of 1, minimum steps required to reach (X, Y) based on the given directions is given by: 
 

Minimum steps = abs(X - i) + abs(Y - j)

Calculate the total number of steps required using the above formula for each cell that contains 1 in the given matrix mat[][].
Below is the implementation of the above approach: 
 

C++




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

Java




// Java program to calculate the
// minimum steps required to reach
// a given cell from all cells
// consisting of 1's
import java.util.*;
 
class GFG{
 
// Function to calculate and
// return the minimum number
// of steps required to move
// all 1s to (X, Y)
static int findAns(int [][]mat,
                   int x, int y,
                   int n, int m)
{
    int ans = 0;
 
    // Iterate the given matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
             
            // Update the answer with
            // minimum moves required
            // for the given element
            // to reach the given index
            if (mat[i][j] == 1)
            {
                ans += Math.abs(x - i) +
                       Math.abs(y - j);
            }
        }
    }
 
    // Return the number
    // of steps
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given matrix
    int [][]mat = { { 1, 0, 0, 0 },
                    { 0, 1, 0, 1 },
                    { 1, 0, 1, 1 } };
 
    // Given position
    int x = 0, y = 2;
 
    // Function Call
    System.out.print(findAns(mat, x, y,
                             mat.length,
                             mat[0].length) + "\n");
}
}
 
// This code is contributed by amal kumar choubey

Python3




# Python3 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 1s to (X, Y)
def findAns(mat, x, y, n, m):
     
    ans = 0
     
    # Iterate the given matrix
    for i in range(n):
        for j in range(m):
             
            # Update the answer with
            # minimum moves required
            # for the given element
            # to reach the given index
            if (mat[i][j] == 1):
                ans += (abs(x - i) +
                        abs(y - j))
     
    # Return the number
    # of steps
    return ans
     
# Driver Code
 
# Given matrix
mat = [ [ 1, 0, 0, 0 ],
        [ 0, 1, 0, 1 ],
        [ 1, 0, 1, 1 ] ]
 
# Given position
x = 0
y = 2
 
# Function call
print(findAns(mat, x, y, len(mat),
                        len(mat[0])))
 
# This code is contributed by shubhamsingh10

C#




// C# program to calculate the
// minimum steps required to reach
// a given cell from all cells
// consisting of 1's
using System;
 
class GFG{
 
// Function to calculate and
// return the minimum number
// of steps required to move
// all 1s to (X, Y)
static int findAns(int [,]mat,
                   int x, int y,
                   int n, int m)
{
    int ans = 0;
 
    // Iterate the given matrix
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
             
            // Update the answer with
            // minimum moves required
            // for the given element
            // to reach the given index
            if (mat[i, j] == 1)
            {
                ans += Math.Abs(x - i) +
                       Math.Abs(y - j);
            }
        }
    }
 
    // Return the number
    // of steps
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given matrix
    int [,]mat = { { 1, 0, 0, 0 },
                   { 0, 1, 0, 1 },
                   { 1, 0, 1, 1 } };
 
    // Given position
    int x = 0, y = 2;
 
    // Function call
    Console.Write(findAns(mat, x, y,
                          mat.GetLength(0),
                          mat.GetLength(1)) + "\n");
}
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
// JavaScript 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 1s to (X, Y)
function findAns(mat, x, y,
                   n, m)
{
    let ans = 0;
 
    // Iterate the given matrix
    for(let i = 0; i < n; i++)
    {
        for(let j = 0; j < m; j++)
        {
             
            // Update the answer with
            // minimum moves required
            // for the given element
            // to reach the given index
            if (mat[i][j] == 1)
            {
                ans += Math.abs(x - i) +
                       Math.abs(y - j);
            }
        }
    }
 
    // Return the number
    // of steps
    return ans;
}
 
// Driver Code
 
    // Given matrix
    let mat = [[ 1, 0, 0, 0 ],
                    [ 0, 1, 0, 1 ],
                    [ 1, 0, 1, 1 ]];
 
    // Given position
    let x = 0, y = 2;
 
    // Function Call
    document.write(findAns(mat, x, y,
                             mat.length,
                             mat[0].length) + "<br/>");
 
</script>

Output: 

15

Time Complexity: O(N*M), since two nested loops are used the time taken by the algorithm to complete all operations is N*M.
Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!