Open In App

Shortest path in a Binary Maze

Last Updated : 18 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
24.69%
1.1L

Given an MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.

Example:

Input:
mat[ROW][COL]  = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
                  {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
                  {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
                  {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
                  {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
                  {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                  {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
Source = {0, 0};
Destination = {3, 4};

Output:
Shortest Path is 11 

Method 1: Using Backtracking

The idea is to use Recursion: 

  1. Start from the given source cell in the matrix and explore all four possible paths.
  2. Check if the destination is reached or not.
  3. Explore all the paths and backtrack if the destination is not reached.
  4. And also keep track of visited cells using an array.
 Valid Moves are:
 left: (i, j) ——> (i, j – 1)
 right: (i, j) ——> (i, j + 1)
 top: (i, j) ——> (i - 1, j)
 bottom: (i, j) ——> (i + 1, j )

Implementation:

C++




#include <iostream>
#include <vector>
#include <climits>
#include <cstring>
using namespace std;
  
// Check if it is possible to go to (x, y) from the current position. The
// function returns false if the cell has value 0 or already visited
bool isSafe(vector<vector<int>> &mat, vector<vector<bool>> &visited, int x, int y)
{
    return (x >= 0 && x < mat.size() && y >= 0 && y < mat[0].size()) &&
            mat[x][y] == 1 && !visited[x][y];
}
  
  
void findShortestPath(vector<vector<int>> &mat, vector<vector<bool>> &visited,
                int i, int j, int x, int y, int &min_dist, int dist){
    if (i == x && j == y){
        min_dist = min(dist, min_dist);
        return;
    }
    // set (i, j) cell as visited
    visited[i][j] = true;
    // go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)) {
        findShortestPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1);
    }
    // go to the right cell
    if (isSafe(mat, visited, i, j + 1)) {
        findShortestPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1);
    }
    // go to the top cell
    if (isSafe(mat, visited, i - 1, j)) {
        findShortestPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1);
    }
    // go to the left cell
    if (isSafe(mat, visited, i, j - 1)) {
        findShortestPath(mat, visited, i, j - 1, x, y, min_dist, dist + 1);
    }
    // backtrack: remove (i, j) from the visited matrix
    visited[i][j] = false;
}
  
// Wrapper over findShortestPath() function
int findShortestPathLength(vector<vector<int>> &mat, pair<int, int> &src,
                    pair<int, int> &dest){
    if (mat.size() == 0 || mat[src.first][src.second] == 0 ||
            mat[dest.first][dest.second] == 0)
        return -1;
     
    int row = mat.size();
    int col = mat[0].size();
    // construct an `M × N` matrix to keep track of visited cells
    vector<vector<bool>> visited;
    visited.resize(row, vector<bool>(col));
  
    int dist = INT_MAX;
    findShortestPath(mat, visited, src.first, src.second, dest.first, dest.second,
            dist, 0);
  
    if (dist != INT_MAX)
        return dist;
    return -1;
}
  
int main()
{
    vector<vector<int>> mat =
    {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
                  {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
                  {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
                  {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
                  {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
                  {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                  {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
  
    pair<int, int> src = make_pair(0, 0);
    pair<int, int> dest = make_pair(3, 4);
    int dist = findShortestPathLength(mat, src, dest);
    if (dist != -1)
        cout << "Shortest Path is " << dist;
     
    else
        cout << "Shortest Path doesn't exist";
   
    return 0;
}


Java




// Java implementation of the code
import java.util.*;
 
class GFG {
 
  static boolean[][] visited;
 
  // Check if it is possible to go to (x, y) from the
  // current position. The function returns false if the
  // cell has value 0 or already visited
  static boolean isSafe(int[][] mat, boolean[][] visited,
                        int x, int y)
  {
    return (x >= 0 && x < mat.length && y >= 0
            && y < mat[0].length && mat[x][y] == 1
            && !visited[x][y]);
  }
 
  static int findShortestPath(int[][] mat, int i, int j,
                              int x, int y, int min_dist,
                              int dist)
  {
 
    if (i == x && j == y) {
      min_dist = Math.min(dist, min_dist);
      return min_dist;
    }
 
    // set (i, j) cell as visited
    visited[i][j] = true;
    // go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)) {
      min_dist = findShortestPath(mat, i + 1, j, x, y,
                                  min_dist, dist + 1);
    }
    // go to the right cell
    if (isSafe(mat, visited, i, j + 1)) {
      min_dist = findShortestPath(mat, i, j + 1, x, y,
                                  min_dist, dist + 1);
    }
    // go to the top cell
    if (isSafe(mat, visited, i - 1, j)) {
      min_dist = findShortestPath(mat, i - 1, j, x, y,
                                  min_dist, dist + 1);
    }
    // go to the left cell
    if (isSafe(mat, visited, i, j - 1)) {
      min_dist = findShortestPath(mat, i, j - 1, x, y,
                                  min_dist, dist + 1);
    }
    // backtrack: remove (i, j) from the visited matrix
    visited[i][j] = false;
    return min_dist;
  }
 
  // Wrapper over findShortestPath() function
  static int findShortestPathLength(int[][] mat,
                                    int[] src, int[] dest)
  {
    if (mat.length == 0 || mat[src[0]][src[1]] == 0
        || mat[dest[0]][dest[1]] == 0)
      return -1;
 
    int row = mat.length;
    int col = mat[0].length;
 
    // construct an `M × N` matrix to keep track of
    // visited cells
    visited = new boolean[row][col];
    for (int i = 0; i < row; i++) {
      for (int j = 0; j < col; j++)
        visited[i][j] = false;
    }
 
    int dist = Integer.MAX_VALUE;
    dist = findShortestPath(mat, src[0], src[1],
                            dest[0], dest[1], dist, 0);
 
    if (dist != Integer.MAX_VALUE)
      return dist;
    return -1;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[][] mat = new int[][] {
      { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
      { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
      { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
      { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
      { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
      { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
      { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
      { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
      { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }
    };
 
    int[] src = { 0, 0 };
    int[] dest = { 3, 4 };
    int dist = findShortestPathLength(mat, src, dest);
    if (dist != -1)
      System.out.print("Shortest Path is " + dist);
 
    else
      System.out.print("Shortest Path doesn't exist");
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 code to implement the approach
import sys
 
# User defined Pair class
class Pair:
    def __init__(self, x, y):
        self.first = x
        self.second = y
 
# Check if it is possible to go to (x, y) from the current
# position. The function returns false if the cell has
# value 0 or already visited
def isSafe(mat, visited, x, y):
    return (x >= 0 and x < len(mat) and y >= 0 and y < len(mat[0]) and mat[x][y] == 1 and (not visited[x][y]))
 
def findShortestPath(mat, visited, i, j, x, y, min_dist, dist):
    if (i == x and j == y):
        min_dist = min(dist, min_dist)
        return min_dist
 
    # set (i, j) cell as visited
    visited[i][j] = True
     
    # go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)):
        min_dist = findShortestPath(
            mat, visited, i + 1, j, x, y, min_dist, dist + 1)
 
    # go to the right cell
    if (isSafe(mat, visited, i, j + 1)):
        min_dist = findShortestPath(
            mat, visited, i, j + 1, x, y, min_dist, dist + 1)
 
    # go to the top cell
    if (isSafe(mat, visited, i - 1, j)):
        min_dist = findShortestPath(
            mat, visited, i - 1, j, x, y, min_dist, dist + 1)
 
    # go to the left cell
    if (isSafe(mat, visited, i, j - 1)):
        min_dist = findShortestPath(
            mat, visited, i, j - 1, x, y, min_dist, dist + 1)
 
    # backtrack: remove (i, j) from the visited matrix
    visited[i][j] = False
    return min_dist
 
# Wrapper over findShortestPath() function
def findShortestPathLength(mat, src, dest):
    if (len(mat) == 0 or mat[src.first][src.second] == 0
            or mat[dest.first][dest.second] == 0):
        return -1
 
    row = len(mat)
    col = len(mat[0])
 
    # construct an `M × N` matrix to keep track of visited
    # cells
    visited = []
    for i in range(row):
        visited.append([None for _ in range(col)])
 
    dist = sys.maxsize
    dist = findShortestPath(mat, visited, src.first,
                            src.second, dest.first, dest.second, dist, 0)
 
    if (dist != sys.maxsize):
        return dist
    return -1
 
# Driver code
mat = [[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
       [1, 0, 1, 0, 1, 1, 1, 0, 1, 1],
       [1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
       [1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 1, 1, 0, 1, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
       [1, 1, 0, 0, 0, 0, 1, 0, 0, 1]
       ]
 
src = Pair(0, 0)
dest = Pair(3, 4)
dist = findShortestPathLength(mat, src, dest)
if (dist != -1):
    print("Shortest Path is", dist)
 
else:
    print("Shortest Path doesn't exist")
 
# This code is contributed by phasing17


C#




// C# implementation of the code
 
using System;
using System.Collections.Generic;
 
class GFG {
 
    static bool[, ] visited;
 
    // Check if it is possible to go to (x, y) from the
    // current position. The function returns false if the
    // cell has value 0 or already visited
    static bool isSafe(int[, ] mat, bool[, ] visited, int x,
                       int y)
    {
        return (x >= 0 && x < mat.GetLength(0) && y >= 0
                && y < mat.GetLength(1) && mat[x, y] == 1
                && !visited[x, y]);
    }
 
    static int findShortestPath(int[, ] mat, int i, int j,
                                int x, int y, int min_dist,
                                int dist)
    {
 
        if (i == x && j == y) {
            min_dist = Math.Min(dist, min_dist);
            return min_dist;
        }
 
        // set (i, j) cell as visited
        visited[i, j] = true;
        // go to the bottom cell
        if (isSafe(mat, visited, i + 1, j)) {
            min_dist = findShortestPath(mat, i + 1, j, x, y,
                                        min_dist, dist + 1);
        }
        // go to the right cell
        if (isSafe(mat, visited, i, j + 1)) {
            min_dist = findShortestPath(mat, i, j + 1, x, y,
                                        min_dist, dist + 1);
        }
        // go to the top cell
        if (isSafe(mat, visited, i - 1, j)) {
            min_dist = findShortestPath(mat, i - 1, j, x, y,
                                        min_dist, dist + 1);
        }
        // go to the left cell
        if (isSafe(mat, visited, i, j - 1)) {
            min_dist = findShortestPath(mat, i, j - 1, x, y,
                                        min_dist, dist + 1);
        }
        // backtrack: remove (i, j) from the visited matrix
        visited[i, j] = false;
        return min_dist;
    }
 
    // Wrapper over findShortestPath() function
    static int findShortestPathLength(int[, ] mat,
                                      int[] src, int[] dest)
    {
        if (mat.GetLength(0) == 0
            || mat[src[0], src[1]] == 0
            || mat[dest[0], dest[1]] == 0)
            return -1;
 
        int row = mat.GetLength(0);
        int col = mat.GetLength(1);
 
        // construct an `M × N` matrix to keep track of
        // visited cells
        visited = new bool[row, col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++)
                visited[i, j] = false;
        }
 
        int dist = Int32.MaxValue;
        dist = findShortestPath(mat, src[0], src[1],
                                dest[0], dest[1], dist, 0);
 
        if (dist != Int32.MaxValue)
            return dist;
        return -1;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[, ] mat = new int[, ] {
            { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
            { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
            { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
            { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
            { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
            { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
            { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
            { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }
        };
 
        int[] src = { 0, 0 };
        int[] dest = { 3, 4 };
        int dist = findShortestPathLength(mat, src, dest);
        if (dist != -1)
            Console.Write("Shortest Path is " + dist);
 
        else
            Console.Write("Shortest Path doesn't exist");
    }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript code to implement the approach
 
 
// User defined Pair class
class Pair {
    constructor(x, y)
    {
        this.first = x;
        this.second = y;
    }
}
 
// Check if it is possible to go to (x, y) from the current
// position. The function returns false if the cell has
// value 0 or already visited
function isSafe(mat, visited, x, y)
{
    return (x >= 0 && x < mat.length && y >= 0
            && y < mat[0].length && mat[x][y] == 1
            && !visited[x][y]);
}
 
function findShortestPath(mat, visited, i, j, x, y,
                          min_dist, dist)
{
    if (i == x && j == y) {
        min_dist = Math.min(dist, min_dist);
        return min_dist;
    }
    // set (i, j) cell as visited
    visited[i][j] = true;
    // go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)) {
        min_dist
            = findShortestPath(mat, visited, i + 1, j, x, y,
                               min_dist, dist + 1);
    }
    // go to the right cell
    if (isSafe(mat, visited, i, j + 1)) {
        min_dist
            = findShortestPath(mat, visited, i, j + 1, x, y,
                               min_dist, dist + 1);
    }
    // go to the top cell
    if (isSafe(mat, visited, i - 1, j)) {
        min_dist
            = findShortestPath(mat, visited, i - 1, j, x, y,
                               min_dist, dist + 1);
    }
    // go to the left cell
    if (isSafe(mat, visited, i, j - 1)) {
        min_dist
            = findShortestPath(mat, visited, i, j - 1, x, y,
                               min_dist, dist + 1);
    }
    // backtrack: remove (i, j) from the visited matrix
    visited[i][j] = false;
    return min_dist;
}
 
// Wrapper over findShortestPath() function
function findShortestPathLength(mat, src, dest)
{
    if (mat.length == 0 || mat[src.first][src.second] == 0
        || mat[dest.first][dest.second] == 0)
        return -1;
 
    let row = mat.length;
    let col = mat[0].length;
    // construct an `M × N` matrix to keep track of visited
    // cells
    let visited = [];
    for (var i = 0; i < row; i++)
        visited.push(new Array(col));
 
    let dist = Number.MAX_SAFE_INTEGER;
    dist = findShortestPath(mat, visited, src.first,
                            src.second, dest.first,
                            dest.second, dist, 0);
 
    if (dist != Number.MAX_SAFE_INTEGER)
        return dist;
    return -1;
}
 
// Driver code
 
let mat = [
    [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
    [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ],
    [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ],
    [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
    [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ],
    [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ],
    [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
    [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
    [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]
];
 
let src = new Pair(0, 0);
let dest = new Pair(3, 4);
let dist = findShortestPathLength(mat, src, dest);
if (dist != -1)
    console.log("Shortest Path is " + dist);
 
else
    console.log("Shortest Path doesn't exist");
 
// This code is contributed by phasing17


Output

Shortest Path is 11

Time complexity: O(4^MN)
Auxiliary Space:  O(M*N)

Method 2: Using BFS

The idea is inspired from Lee algorithm and uses BFS.  

  1. We start from the source cell and call the BFS procedure.
  2. We maintain a queue to store the coordinates of the matrix and initialize it with the source cell.
  3. We also maintain a Boolean array visited of the same size as our input matrix and initialize all its elements to false.
    1. We LOOP till queue is not empty
    2. Dequeue front cell from the queue
    3. Return if the destination coordinates have been reached.
    4. For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited.

Note that BFS works here because it doesn’t consider a single path at once. It considers all the paths starting from the source and moves ahead one unit in all those paths at the same time which makes sure that the first time when the destination is visited, it is the shortest path.
Below is the implementation of the idea –  

Implementation:

C++




// C++ program to find the shortest path between
// a given source cell to a destination cell.
#include <bits/stdc++.h>
using namespace std;
#define ROW 9
#define COL 10
 
//To store matrix cell coordinates
struct Point
{
    int x;
    int y;
};
 
// A Data Structure for queue used in BFS
struct queueNode
{
    Point pt;  // The coordinates of a cell
    int dist;  // cell's distance of from the source
};
 
// check whether given cell (row, col) is a valid
// cell or not.
bool isValid(int row, int col)
{
    // return true if row number and column number
    // is in range
    return (row >= 0) && (row < ROW) &&
           (col >= 0) && (col < COL);
}
 
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
int rowNum[] = {-1, 0, 0, 1};
int colNum[] = {0, -1, 1, 0};
 
// function to find the shortest path between
// a given source cell to a destination cell.
int BFS(int mat[][COL], Point src, Point dest)
{
    // check source and destination cell
    // of the matrix have value 1
    if (!mat[src.x][src.y] || !mat[dest.x][dest.y])
        return -1;
 
    bool visited[ROW][COL];
    memset(visited, false, sizeof visited);
     
    // Mark the source cell as visited
    visited[src.x][src.y] = true;
 
    // Create a queue for BFS
    queue<queueNode> q;
     
    // Distance of source cell is 0
    queueNode s = {src, 0};
    q.push(s);  // Enqueue source cell
 
    // Do a BFS starting from source cell
    while (!q.empty())
    {
        queueNode curr = q.front();
        Point pt = curr.pt;
 
        // If we have reached the destination cell,
        // we are done
        if (pt.x == dest.x && pt.y == dest.y)
            return curr.dist;
 
        // Otherwise dequeue the front
        // cell in the queue
        // and enqueue its adjacent cells
        q.pop();
 
        for (int i = 0; i < 4; i++)
        {
            int row = pt.x + rowNum[i];
            int col = pt.y + colNum[i];
             
            // if adjacent cell is valid, has path and
            // not visited yet, enqueue it.
            if (isValid(row, col) && mat[row][col] &&
               !visited[row][col])
            {
                // mark cell as visited and enqueue it
                visited[row][col] = true;
                queueNode Adjcell = { {row, col},
                                      curr.dist + 1 };
                q.push(Adjcell);
            }
        }
    }
 
    // Return -1 if destination cannot be reached
    return -1;
}
 
// Driver program to test above function
int main()
{
    int mat[ROW][COL] =
    {
        { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
        { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
        { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
        { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
        { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
        { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
        { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
        { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
        { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }
    };
 
    Point source = {0, 0};
    Point dest = {3, 4};
 
    int dist = BFS(mat, source, dest);
 
    if (dist != -1)
        cout << "Shortest Path is " << dist ;
    else
        cout << "Shortest Path doesn't exist";
 
    return 0;
}


Java




// Java program to find the shortest
// path between a given source cell
// to a destination cell.
import java.util.*;
 
class GFG
{
static int ROW = 9;
static int COL = 10;
 
// To store matrix cell coordinates
static class Point
{
    int x;
    int y;
 
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
};
 
// A Data Structure for queue used in BFS
static class queueNode
{
    Point pt; // The coordinates of a cell
    int dist; // cell's distance of from the source
 
    public queueNode(Point pt, int dist)
    {
        this.pt = pt;
        this.dist = dist;
    }
};
 
// check whether given cell (row, col)
// is a valid cell or not.
static boolean isValid(int row, int col)
{
    // return true if row number and
    // column number is in range
    return (row >= 0) && (row < ROW) &&
           (col >= 0) && (col < COL);
}
 
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
static int rowNum[] = {-1, 0, 0, 1};
static int colNum[] = {0, -1, 1, 0};
 
// function to find the shortest path between
// a given source cell to a destination cell.
static int BFS(int mat[][], Point src,
                            Point dest)
{
    // check source and destination cell
    // of the matrix have value 1
    if (mat[src.x][src.y] != 1 ||
        mat[dest.x][dest.y] != 1)
        return -1;
 
    boolean [][]visited = new boolean[ROW][COL];
     
    // Mark the source cell as visited
    visited[src.x][src.y] = true;
 
    // Create a queue for BFS
    Queue<queueNode> q = new LinkedList<>();
     
    // Distance of source cell is 0
    queueNode s = new queueNode(src, 0);
    q.add(s); // Enqueue source cell
 
    // Do a BFS starting from source cell
    while (!q.isEmpty())
    {
        queueNode curr = q.peek();
        Point pt = curr.pt;
 
        // If we have reached the destination cell,
        // we are done
        if (pt.x == dest.x && pt.y == dest.y)
            return curr.dist;
 
        // Otherwise dequeue the front cell
        // in the queue and enqueue
        // its adjacent cells
        q.remove();
 
        for (int i = 0; i < 4; i++)
        {
            int row = pt.x + rowNum[i];
            int col = pt.y + colNum[i];
             
            // if adjacent cell is valid, has path
            // and not visited yet, enqueue it.
            if (isValid(row, col) &&
                    mat[row][col] == 1 &&
                    !visited[row][col])
            {
                // mark cell as visited and enqueue it
                visited[row][col] = true;
                queueNode Adjcell = new queueNode
                             (new Point(row, col),
                                   curr.dist + 1 );
                q.add(Adjcell);
            }
        }
    }
 
    // Return -1 if destination cannot be reached
    return -1;
}
 
// Driver Code
public static void main(String[] args)
{
    int mat[][] = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                   { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
                   { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
                   { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
                   { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
                   { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
                   { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                   { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                   { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
 
    Point source = new Point(0, 0);
    Point dest = new Point(3, 4);
 
    int dist = BFS(mat, source, dest);
 
    if (dist != -1)
        System.out.println("Shortest Path is " + dist);
    else
        System.out.println("Shortest Path doesn't exist");
    }
}
 
// This code is contributed by PrinciRaj1992


Python




# Python program to find the shortest
# path between a given source cell
# to a destination cell.
 
from collections import deque
ROW = 9
COL = 10
 
# To store matrix cell coordinates
class Point:
    def __init__(self,x: int, y: int):
        self.x = x
        self.y = y
 
# A data structure for queue used in BFS
class queueNode:
    def __init__(self,pt: Point, dist: int):
        self.pt = pt  # The coordinates of the cell
        self.dist = dist  # Cell's distance from the source
 
# Check whether given cell(row,col)
# is a valid cell or not
def isValid(row: int, col: int):
    return (row >= 0) and (row < ROW) and
                   (col >= 0) and (col < COL)
 
# These arrays are used to get row and column
# numbers of 4 neighbours of a given cell
rowNum = [-1, 0, 0, 1]
colNum = [0, -1, 1, 0]
 
# Function to find the shortest path between
# a given source cell to a destination cell.
def BFS(mat, src: Point, dest: Point):
     
    # check source and destination cell
    # of the matrix have value 1
    if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1:
        return -1
     
    visited = [[False for i in range(COL)]
                       for j in range(ROW)]
     
    # Mark the source cell as visited
    visited[src.x][src.y] = True
     
    # Create a queue for BFS
    q = deque()
     
    # Distance of source cell is 0
    s = queueNode(src,0)
    q.append(s) #  Enqueue source cell
     
    # Do a BFS starting from source cell
    while q:
 
        curr = q.popleft() # Dequeue the front cell
         
        # If we have reached the destination cell,
        # we are done
        pt = curr.pt
        if pt.x == dest.x and pt.y == dest.y:
            return curr.dist
         
        # Otherwise enqueue its adjacent cells
        for i in range(4):
            row = pt.x + rowNum[i]
            col = pt.y + colNum[i]
             
            # if adjacent cell is valid, has path 
            # and not visited yet, enqueue it.
            if (isValid(row,col) and
               mat[row][col] == 1 and
                not visited[row][col]):
                visited[row][col] = True
                Adjcell = queueNode(Point(row,col),
                                    curr.dist+1)
                q.append(Adjcell)
     
    # Return -1 if destination cannot be reached
    return -1
 
# Driver code
def main():
    mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
           [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ],
           [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ],
           [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
           [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ],
           [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ],
           [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
           [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
           [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]]
    source = Point(0,0)
    dest = Point(3,4)
     
    dist = BFS(mat,source,dest)
     
    if dist!=-1:
        print("Shortest Path is",dist)
    else:
        print("Shortest Path doesn't exist")
main()
 
# This code is contributed by stutipathak31jan


C#




// C# program to find the shortest
// path between a given source cell
// to a destination cell.
using System;
using System.Collections.Generic;
 
class GFG
{
static int ROW = 9;
static int COL = 10;
 
// To store matrix cell coordinates
public class Point
{
    public int x;
    public int y;
 
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
};
 
// A Data Structure for queue used in BFS
public class queueNode
{
    // The coordinates of a cell
    public Point pt;
     
    // cell's distance of from the source
    public int dist;
 
    public queueNode(Point pt, int dist)
    {
        this.pt = pt;
        this.dist = dist;
    }
};
 
// check whether given cell (row, col)
// is a valid cell or not.
static bool isValid(int row, int col)
{
    // return true if row number and
    // column number is in range
    return (row >= 0) && (row < ROW) &&
           (col >= 0) && (col < COL);
}
 
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
static int []rowNum = {-1, 0, 0, 1};
static int []colNum = {0, -1, 1, 0};
 
// function to find the shortest path between
// a given source cell to a destination cell.
static int BFS(int [,]mat, Point src,
                           Point dest)
{
    // check source and destination cell
    // of the matrix have value 1
    if (mat[src.x, src.y] != 1 ||
        mat[dest.x, dest.y] != 1)
        return -1;
 
    bool [,]visited = new bool[ROW, COL];
     
    // Mark the source cell as visited
    visited[src.x, src.y] = true;
 
    // Create a queue for BFS
    Queue<queueNode> q = new Queue<queueNode>();
     
    // Distance of source cell is 0
    queueNode s = new queueNode(src, 0);
    q.Enqueue(s); // Enqueue source cell
 
    // Do a BFS starting from source cell
    while (q.Count != 0)
    {
        queueNode curr = q.Peek();
        Point pt = curr.pt;
 
        // If we have reached the destination cell,
        // we are done
        if (pt.x == dest.x && pt.y == dest.y)
            return curr.dist;
 
        // Otherwise dequeue the front cell
        // in the queue and enqueue
        // its adjacent cells
        q.Dequeue();
 
        for (int i = 0; i < 4; i++)
        {
            int row = pt.x + rowNum[i];
            int col = pt.y + colNum[i];
             
            // if adjacent cell is valid, has path
            // and not visited yet, enqueue it.
            if (isValid(row, col) &&
                    mat[row, col] == 1 &&
               !visited[row, col])
            {
                // mark cell as visited and enqueue it
                visited[row, col] = true;
                queueNode Adjcell = new queueNode
                           (new Point(row, col),
                                curr.dist + 1 );
                q.Enqueue(Adjcell);
            }
        }
    }
 
    // Return -1 if destination cannot be reached
    return -1;
}
 
// Driver Code
public static void Main(String[] args)
{
    int [,]mat = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
                   { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
                  { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
                  { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
                  { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
                  { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                  { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
                  { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
 
    Point source = new Point(0, 0);
    Point dest = new Point(3, 4);
 
    int dist = BFS(mat, source, dest);
 
    if (dist != -1)
        Console.WriteLine("Shortest Path is " + dist);
    else
        Console.WriteLine("Shortest Path doesn't exist");
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to find the shortest
// path between a given source cell
// to a destination cell.
 
const ROW = 9
const COL = 10
 
// To store matrix cell coordinates
class Point{
    constructor(x, y){
        this.x = x
        this.y = y
    }
}
 
// A data structure for queue used in BFS
class queueNode{
    constructor(pt, dist){
        this.pt = pt // The coordinates of the cell
        this.dist = dist // Cell's distance from the source
    }
}
 
// Check whether given cell(row,col)
// is a valid cell or not
function isValid(row, col){
    return (row >= 0) && (row < ROW) &&
                (col >= 0) && (col < COL)
}
 
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
let rowNum = [-1, 0, 0, 1]
let colNum = [0, -1, 1, 0]
 
// Function to find the shortest path between
// a given source cell to a destination cell.
function BFS(mat, src, dest){
     
    // check source and destination cell
    // of the matrix have value 1
    if(mat[src.x][src.y]!=1 || mat[dest.x][dest.y]!=1)
        return -1
     
    let visited = new Array(ROW).fill(false).map(()=>new Array(COL).fill(false));
     
    // Mark the source cell as visited
    visited[src.x][src.y] = true
     
    // Create a queue for BFS
    let q = []
     
    // Distance of source cell is 0
    let s = new queueNode(src,0)
    q.push(s) // Enqueue source cell
     
    // Do a BFS starting from source cell
    while(q){
 
        let curr = q.shift() // Dequeue the front cell
         
        // If we have reached the destination cell,
        // we are done
        let pt = curr.pt
        if(pt.x == dest.x && pt.y == dest.y)
            return curr.dist
         
        // Otherwise enqueue its adjacent cells
        for(let i=0;i<4;i++){
            let row = pt.x + rowNum[i]
            let col = pt.y + colNum[i]
             
            // if adjacent cell is valid, has path
            // and not visited yet, enqueue it.
            if (isValid(row,col) && mat[row][col] == 1 && !visited[row][col]){
                visited[row][col] = true
                let Adjcell = new queueNode(new Point(row,col),
                                    curr.dist+1)
                q.push(Adjcell)
            }
        }
    }
    // Return -1 if destination cannot be reached
    return -1
}
 
// Driver code
function main(){
     
let mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
        [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ],
        [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ],
        [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
        [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ],
        [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ],
        [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
        [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
        [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]]
     
let source = new Point(0,0)
let dest = new Point(3,4)
     
let dist = BFS(mat,source,dest)
     
if(dist!=-1)
    document.write("Shortest Path is",dist,"</br>")
else
    document.write("Shortest Path doesn't exist","</br>")
}
 
main()
     
// This code is contributed by shinjanpatra
 
</script>


Output

Shortest Path is 11

Time complexity: O(M*N)
Auxiliary Space: O(M*N)



Previous Article
Next Article

Similar Reads

Time saved travelling in shortest route and shortest path through given city
Given a matrix mat[][] of size N * N, where mat[i][j] represents the time taken to reach from ith city to jth city. Also, given M queries in the form of three arrays S[], I[], and D[] representing source, intermediate, and destination respectively. The task is to find the time taken to go from S[i] to D[i] using I[i] city and the time that can be s
10 min read
Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph
Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does not contain multiple edges and self loops. (2<=N
15+ min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) > Weight(E2) < Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1s
Given a binary matrix mat[][] of dimensions of N * M and pairs of integers src and dest representing source and destination cells respectively, the task is to find the shortest sequence of moves from the given source cell to the destination cell via cells consisting only of 1s. The allowed moves are moving a cell left (L), right (R), up (U), and do
15+ min read
Step by step Shortest Path from source node to destination node in a Binary Tree
Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below. Going from one node to its left child node is indicated by the letter 'L'.Going from one node to
14 min read
Shortest path between two nodes in array like representation of binary tree
Consider a binary tree in which each node has two children except the leaf nodes. If a node is labeled as 'v' then its right children will be labeled as 2v+1 and left children as 2v. Root is labelled asGiven two nodes labeled as i and j, the task is to find the shortest distance and the path from i to j. And print the path of node i and node j from
12 min read
0-1 BFS (Shortest Path in a Binary Weight Graph)
Given a graph where every edge has weight as either 0 or 1. A source vertex is also given in the graph. Find the shortest path from the source vertex to every other vertex.  For Example:  Input : Source Vertex = 0 and below graph Having vertices like(u,v,w): Edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1], [2, 3, 0], [2, 5, 0], [2, 8, 1], [3, 4, 1],
9 min read
Print the first shortest root to leaf path in a Binary Tree
Given a Binary Tree with distinct values, the task is to find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes. The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the minimum number of nodes. The root to leaf path in bel
8 min read
Some interesting shortest path questions | Set 1
Question 1: Given a directed weighted graph. You are also given the shortest path from a source vertex 's' to a destination vertex 't'. If weight of every edge is increased by 10 units, does the shortest path remain same in the modified graph? The shortest path may change. The reason is, there may be different number of edges in different paths fro
3 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Probabilistic shortest path routing algorithm for optical networks
Data transfer operations is a crucial aspect in case of networking and routing. So efficient data transfer operations is a must need, with minimum hardware cost (Optical Cables, WDM Network components, Decoders, Multiplexers) and also in the minimum time possible. Thus, the need is to propose an algorithm that finds the shortest path between two no
5 min read
Minimum length of the shortest path of a triangle
Given N points on the plane, ( X1, Y1 ), ( X2, Y2 ), ( X3, Y3 ), ......, ( XN, YN ). The task is to calculate the minimum length of the shorter side of the triangle. and the path or points to place an isosceles triangle with any two sides of the triangle on the coordinate axis ( X axis and Y axis ) to cover all points.Note: A point is covered if it
7 min read
Dijkstra's shortest path with minimum edges
Prerequisite: Dijkstra’s shortest path algorithm Given an adjacency matrix graph representing paths between the nodes in the given graph. The task is to find the shortest path with minimum edges i.e. if there a multiple short paths with same cost then choose the one with the minimum number of edges. Consider the graph given below: There are two pat
13 min read
Shortest root to leaf path sum equal to a given number
Given a binary tree and a number, the task is to return the length of the shortest path beginning at the root and ending at a leaf node such that the sum of numbers along that path is equal to ‘sum’. Print "-1" if no such path exists. Examples: Input: 1 / \ 10 15 / \ 5 2 Number = 16 Output: 2 There are two paths: 1->15, length of path is 3 1-
9 min read
Shortest Path using Meet In The Middle
Given a permutation P = p1, p2, ...., pn of first n natural numbers (1 ? n ? 10). One can swap any two consecutive elements pi and pi + 1 (1 ? i < n). The task is to find the minimum number of swaps to change P to another permutation P' = p'1, p'2, ...., p'n. Examples: Input: P = "213", P' = "321"Output: 2213 <-> 231 <-> 321 Input: P
8 min read
Shortest path to traverse all the elements of a circular array in increasing order
There are N distinct integers arranged on a circle. The distance between any two adjacent numbers is 1. The task is to travel on this circle starting with the smallest number, then moving to the second smallest, third smallest, and so on until the largest number and print the minimum travel distance. Examples: Input: arr[] = {3, 6, 5, 1, 2, 4} Outp
6 min read
Check if given path between two nodes of a graph represents a shortest paths
Given an unweighted directed graph and Q queries consisting of sequences of traversal between two nodes of the graph, the task is to find out if the sequences represent one of the shortest paths between the two nodes.Examples: Input: 1 2 3 4 Output: NOExplanation: The first and last node of the input sequence is 1 and 4 respectively. The shortest p
8 min read
Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1. Note: K will always be lesser than 2 * N. Examples: Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1,
8 min read
Shortest path with exactly k edges in a directed and weighted graph | Set 2
Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1->2->3
8 min read
Maximize shortest path between given vertices by adding a single edge
Given an undirected graph of N nodes and M vertices. You are also given a K edges as selected[]. The task to maximize the shortest path length between node 1 to node N by adding single edges between any two vertices from the given selected edges. Note: You may add an edge between any two selected vertices who have already an edge between them. Inpu
11 min read
Shortest Path with even number of Edges from Source to Destination
Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path). Examples: Input: N = 5, G is given below: Output: 10 Explanation: All paths from 1(source node) to 5 (destination node) are: 1-
13 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Shortest path length between two given nodes such that adjacent nodes are at bit difference 2
Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and b, then print -1. Examples: Input: N = 15, a = 15
7 min read
Single source shortest path between two cities
Given a graph of N Nodes and E edges in form of {U, V, W} such that there exists an edge between U and V with weight W. You are given an integer K and source src and destination dst. The task is to find the cheapest cost path from given source to destination from K stops.Examples: Input: N = 3, edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]], src =
15+ min read
Create a Graph by connecting divisors from N to M and find shortest path
Given two natural numbers N and M, Create a graph using these two natural numbers using relation that a number is connected to its largest factor other than itself. The task is to find the shortest path between these two numbers after creating a graph. Examples: Input: N = 6, M = 18Output: 6 <--> 3 <--> 9 <--> 18Explanation:For N
12 min read
Applications of Dijkstra's shortest path algorithm
Dijkstra’s algorithm is one of the most popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. Dijkstra’s Algori
4 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Difference between Minimum Spanning Tree and Shortest Path
Spanning tree: A spanning tree (T) of an undirected graph(G) is a subgraph which is a tree that includes all the vertices of a graph (G) and the minimum number of edges required to connect the graph (G). And it is a known maximal set of edges with no cycles. Properties: If a graph(G) is not connected then it does not contain a spanning tree (i.e. i
4 min read
Shortest path for a thief to reach the Nth house avoiding policemen
Given an unweighted graph and a boolean array A[ ], where if the ith index of array A[ ] denotes if that node can be visited (0) or not (1). The task is to find the shortest path to reach (N - 1)th node from the 0th node. If it is not possible to reach, print -1. Examples : Input : N = 5, A[] = {0, 1, 0, 0, 0}, Edges = {{0, 1}, {0, 2}, {1, 4}, {2,
11 min read
Shortest Path Properties
The shortest path problem is the problem of finding a path between two vertices (or nodes) in a graph such that the sum of the weights of its constituent edges is minimized. The shortest path between any two nodes of the graph can be founded using many algorithms, such as Dijkstra's algorithm, Bellman-Ford algorithm, Floyd Warshall algorithm. There
2 min read
three90RightbarBannerImg