C++ Program for Shortest distance between two cells in a matrix or grid
Last Updated :
17 Aug, 2023
Given a matrix of N*M order. Find the shortest distance from a source cell to a destination cell, traversing through limited cells only. Also you can move only up, down, left and right. If found output the distance else -1.
s represents 'source'
d represents 'destination'
* represents cell you can travel
0 represents cell you can not travel
This problem is meant for single source and destination.
Examples:
Input : {'0', '*', '0', 's'},
{'*', '0', '*', '*'},
{'0', '*', '*', '*'},
{'d', '*', '*', '*'}
Output : 6
Input : {'0', '*', '0', 's'},
{'*', '0', '*', '*'},
{'0', '*', '*', '*'},
{'d', '0', '0', '0'}
Output : -1
The idea is to BFS (breadth first search) on matrix cells. Note that we can always use BFS to find shortest path if graph is unweighted.
- Store each cell as a node with their row, column values and distance from source cell.
- Start BFS with source cell.
- Make a visited array with all having "false" values except '0'cells which are assigned "true" values as they can not be traversed.
- Keep updating distance from source value in each move.
- Return distance when destination is met, else return -1 (no path exists in between source and destination).
CPP
// C++ Code implementation for above problem
#include <bits/stdc++.h>
using namespace std;
#define N 4
#define M 4
// QItem for current location and distance
// from source location
class QItem {
public:
int row;
int col;
int dist;
QItem(int x, int y, int w)
: row(x), col(y), dist(w)
{
}
};
int minDistance(char grid[N][M])
{
QItem source(0, 0, 0);
// To keep track of visited QItems. Marking
// blocked cells as visited.
bool visited[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
{
if (grid[i][j] == '0')
visited[i][j] = true;
else
visited[i][j] = false;
// Finding source
if (grid[i][j] == 's')
{
source.row = i;
source.col = j;
}
}
}
// applying BFS on matrix cells starting from source
queue<QItem> q;
q.push(source);
visited[source.row][source.col] = true;
while (!q.empty()) {
QItem p = q.front();
q.pop();
// Destination found;
if (grid[p.row][p.col] == 'd')
return p.dist;
// moving up
if (p.row - 1 >= 0 &&
visited[p.row - 1][p.col] == false) {
q.push(QItem(p.row - 1, p.col, p.dist + 1));
visited[p.row - 1][p.col] = true;
}
// moving down
if (p.row + 1 < N &&
visited[p.row + 1][p.col] == false) {
q.push(QItem(p.row + 1, p.col, p.dist + 1));
visited[p.row + 1][p.col] = true;
}
// moving left
if (p.col - 1 >= 0 &&
visited[p.row][p.col - 1] == false) {
q.push(QItem(p.row, p.col - 1, p.dist + 1));
visited[p.row][p.col - 1] = true;
}
// moving right
if (p.col + 1 < M &&
visited[p.row][p.col + 1] == false) {
q.push(QItem(p.row, p.col + 1, p.dist + 1));
visited[p.row][p.col + 1] = true;
}
}
return -1;
}
// Driver code
int main()
{
char grid[N][M] = { { '0', '*', '0', 's' },
{ '*', '0', '*', '*' },
{ '0', '*', '*', '*' },
{ 'd', '*', '*', '*' } };
cout << minDistance(grid);
return 0;
}
Output:
6
Please refer complete article on
Shortest distance between two cells in a matrix or grid for more details!
Similar Reads
Number of cells in matrix which are equidistant from given two points Given a matrix of N rows and M columns, given two points on the matrix; the task is to count the number of cells that are equidistant from given two points. Any traversal either in the horizontal direction or vertical direction or both ways is considered valid but the diagonal path is not valid.Exam
5 min read
Number of shortest paths to reach every cell from bottom-left cell in the grid Given two number N and M. The task is to find the number of shortest paths to reach the cell(i, j) in the grid of size N Ã M when the moves started from the bottom-left cornerNote: cell(i, j) represents the ith row and jth column in the gridBelow image shows some of the shortest paths to reach cell(
6 min read
Minimum Numbers of cells that are connected with the smallest path between 3 given cells Given coordinates of 3 cells (X1, Y1), (X2, Y2) and (X3, Y3) of a matrix. The task is to find the minimum path which connects all three of these cells and print the count of all the cells that are connected through this path. Note: Only possible moves are up, down, left and right. Examples: Input: X
7 min read
C++ Program to Implement Adjacency Matrix An adjacency matrix is a way to represent graph data structure in C++ in the form of a two-dimensional matrix. It is a simple square matrix of size V*V, where V represents the number of vertices in the graph. Each cell of the matrix represents an edge between the row vertex and column vertex of the
4 min read
C++ Program to Print matrix in zag-zag fashion Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: 1 2 3 4 5 6 7 8 9 Output: 1 2 4 7 5 3 6 8 9 Approach of C++ code The approach is simple. Just simply iterate over every diagonal elements one at a time and change the directio
3 min read