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).

`// 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; ` `} ` |

*chevron_right*

*filter_none*

Output:

6

This article is contributed by **Prashant Singh**. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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:

- 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
- Minimum Numbers of cells that are connected with the smallest path between 3 given cells
- Minimum Distance from a given Cell to all other Cells of a Matrix
- Check if cells numbered 1 to K in a grid can be connected after removal of atmost one blocked cell
- Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted
- Color a grid such that all same color cells are connected either horizontally or vertically
- Find whether there is path between two cells in matrix
- Number of cells in matrix which are equidistant from given two points
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups
- Minimum distance to the end of a grid from source
- Minimum distance to the corner of a grid from source
- Print cells with same rectangular sums in a matrix
- Unique cells in a binary matrix
- Number of cells in the right and left diagonals passing through (x, y) in a matrix
- Find safe cells in a matrix
- Find Number of Even cells in a Zero Matrix after Q queries
- Number of cells in a matrix that satisfy the given condition
- Total number of cells covered in a matrix after D days