Given two integers R and C, denoting the number of rows and columns in a matrix, and two integers X and Y, the task is to find the minimum distance from the given cell to all other cells of the matrix.
Examples:
Input: R = 5, C = 5, X = 2, Y = 2
Output:
2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2Input: R = 5, C = 5, X = 1, Y = 1
Output:
1 1 1 2 3
1 0 1 2 3
1 1 1 2 3
2 2 2 2 3
3 3 3 3 3
Approach:
Follow the steps below to solve the problem:
- Assign the distance of the initial cells as 0.
- Initialize a Queue and insert the pair {X, Y} into the Queue.
- Iterate until the Queue is not empty, and for every unvisited cell, assign the current distance and insert the index {i, j} into the Queue using BFS technique.
- Print the distance of each cell at the end.
Below is the implementation of the above approach:
C++
// C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std; int mat[1001][1001]; int r, c, x, y; // Stores the accessible directions int dx[] = { 0, -1, -1, -1, 0, 1, 1, 1 }; int dy[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; // Function to find the minimum distance from a // given cell to all other cells in the matrix void FindMinimumDistance() { // Stores the accessible cells // from current cell queue<pair<int, int> > q; // Insert pair (x, y) q.push({ x, y }); mat[x][y] = 0; // Iterate untill queue is empty while (!q.empty()) { // Extract the pair x = q.front().first; y = q.front().second; // Pop them q.pop(); for (int i = 0; i < 8; i++) { int a = x + dx[i]; int b = y + dy[i]; // Checking boundary condition if (a < 0 || a >= r || b >= c || b < 0) continue; // If the cell is not visited if (mat[a][b] == 0) { // Assign the minimum distance mat[a][b] = mat[x][y] + 1; // Insert the traversed neighbour // into the queue q.push({ a, b }); } } } } // Driver Code int main() { r = 5, c = 5, x = 1, y = 1; int t = x; int l = y; mat[x][y] = 0; FindMinimumDistance(); mat[t][l] = 0; // Print the required distances for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << mat[i][j] << " "; } cout << endl; } } |
Java
// Java program to implement // the above approach import java.util.*; class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int [][]mat = new int[1001][1001]; static int r, c, x, y; // Stores the accessible directions static int dx[] = { 0, -1, -1, -1, 0, 1, 1, 1 }; static int dy[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; // Function to find the minimum distance from a // given cell to all other cells in the matrix static void FindMinimumDistance() { // Stores the accessible cells // from current cell Queue<pair> q = new LinkedList<>(); // Insert pair (x, y) q.add(new pair(x, y)); mat[x][y] = 0; // Iterate untill queue is empty while (!q.isEmpty()) { // Extract the pair x = q.peek().first; y = q.peek().second; // Pop them q.remove(); for(int i = 0; i < 8; i++) { int a = x + dx[i]; int b = y + dy[i]; // Checking boundary condition if (a < 0 || a >= r || b >= c || b < 0) continue; // If the cell is not visited if (mat[a][b] == 0) { // Assign the minimum distance mat[a][b] = mat[x][y] + 1; // Insert the traversed neighbour // into the queue q.add(new pair(a, b)); } } } } // Driver Code public static void main(String[] args) { r = 5; c = 5; x = 1; y = 1; int t = x; int l = y; mat[x][y] = 0; FindMinimumDistance(); mat[t][l] = 0; // Print the required distances for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { System.out.print(mat[i][j] + " "); } System.out.println(); } } } // This code is contributed by Amit Katiyar |
Python3
# Python3 program to implement # the above approach mat = [[0 for x in range(1001)] for y in range(1001)] # Stores the accessible directions dx = [ 0, -1, -1, -1, 0, 1, 1, 1 ] dy = [ 1, 1, 0, -1, -1, -1, 0, 1 ] # Function to find the minimum distance # from a given cell to all other cells # in the matrix def FindMinimumDistance(): global x, y, r, c # Stores the accessible cells # from current cell q = [] # Insert pair (x, y) q.append([x, y]) mat[x][y] = 0 # Iterate untill queue is empty while(len(q) != 0): # Extract the pair x = q[0][0] y = q[0][1] # Pop them q.pop(0) for i in range(8): a = x + dx[i] b = y + dy[i] # Checking boundary condition if(a < 0 or a >= r or b >= c or b < 0): continue # If the cell is not visited if(mat[a][b] == 0): # Assign the minimum distance mat[a][b] = mat[x][y] + 1 # Insert the traversed neighbour # into the queue q.append([a, b]) # Driver Code r = 5c = 5x = 1y = 1t = x l = y mat[x][y] = 0 FindMinimumDistance() mat[t][l] = 0 # Print the required distances for i in range(r): for j in range(c): print(mat[i][j], end = " ") print() # This code is contributed by Shivam Singh |
C#
// C# program to implement // the above approach using System; using System.Collections.Generic; class GFG{ class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int [,]mat = new int[1001, 1001]; static int r, c, x, y; // Stores the accessible directions static int []dx = { 0, -1, -1, -1, 0, 1, 1, 1 }; static int []dy = { 1, 1, 0, -1, -1, -1, 0, 1 }; // Function to find the minimum distance from a // given cell to all other cells in the matrix static void FindMinimumDistance() { // Stores the accessible cells // from current cell Queue<pair> q = new Queue<pair>(); // Insert pair (x, y) q.Enqueue(new pair(x, y)); mat[x, y] = 0; // Iterate untill queue is empty while (q.Count != 0) { // Extract the pair x = q.Peek().first; y = q.Peek().second; // Pop them q.Dequeue(); for(int i = 0; i < 8; i++) { int a = x + dx[i]; int b = y + dy[i]; // Checking boundary condition if (a < 0 || a >= r || b >= c || b < 0) continue; // If the cell is not visited if (mat[a, b] == 0) { // Assign the minimum distance mat[a, b] = mat[x, y] + 1; // Insert the traversed neighbour // into the queue q.Enqueue(new pair(a, b)); } } } } // Driver Code public static void Main(String[] args) { r = 5; c = 5; x = 1; y = 1; int t = x; int l = y; mat[x, y] = 0; FindMinimumDistance(); mat[t, l] = 0; // Print the required distances for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); } } } // This code is contributed by shikhasingrajput |
1 1 1 2 3 1 0 1 2 3 1 1 1 2 3 2 2 2 2 3 3 3 3 3 3
Time Complexity: O(R * C)
Auxiliary Space: O(R * C)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimum moves taken to move coin of each cell to any one cell of Matrix
- Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix
- Minimum Numbers of cells that are connected with the smallest path between 3 given cells
- Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added
- Count of cells in a matrix whose adjacent cells's sum is prime Number
- Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
- Minimum cells traversed to reach corner where every cell represents jumps
- Minimum cells required to reach destination with jumps equal to cell values
- Longest subarray of non-empty cells after removal of at most a single empty cell
- Check if cells numbered 1 to K in a grid can be connected after removal of atmost one blocked cell
- Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Shortest distance between two cells in a matrix or grid
- Distance of nearest cell having 1 in a binary matrix
- Find minimum moves to bring all elements in one cell of a matrix
- Find sum of all elements in a matrix except the elements in row and/or column of given cell?
- Sum of cost of all paths to reach a given cell in a Matrix
- Find the minimum number of moves needed to move from one cell of matrix to another
- Size of all connected non-empty cells of a Matrix
- Number of cells in a matrix that satisfy the given condition
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

