Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Minimum cost to traverse from one index to another in the String
Next article icon

Shortest path in a Binary Maze

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an M x N 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.

Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and Right if that adjacent cell is filled with element 1.

Example:

Input: mat[][] = [[1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 1, 1], [1, 1, 0, 0], [1, 0, 0, 1]], source = [0, 1], destination = {2, 2}
Output: 3
Explanation: The path is (0, 1) -> (1, 1) -> (2, 1) – > (2, 2) (the same is highlighted below)
1 1 1 1
1 1 0 1
1 1 1 1
1 1 0 0
1 0 0 1

Input: mat[][] = [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0 ] , [1, 0, 1, 0, 1]], source = {0, 0}, destination = {3, 4}
Output: -1
Explanation: The path is not possible between source and destination, hence return -1.

[Naive Approach] – Using DFS

The idea for this approach is to use Recursion to explore all possible paths at every step starting from the given source cell in the matrix and backtrack if the destination is not reached and also keep track of visited cells using an array.

C++
#include <bits/stdc++.h> 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 shortPath(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)) {         shortPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1);     }          // go to the right cell     if (isSafe(mat, visited, i, j + 1)) {         shortPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1);     }          // go to the top cell     if (isSafe(mat, visited, i - 1, j)) {         shortPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1);     }          // go to the left cell     if (isSafe(mat, visited, i, j - 1)) {         shortPath(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 shortPath() function int shortPathLength(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;     shortPath(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 = shortPathLength(mat, src, dest);     cout << dist;         return 0; } 
Java
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 shortPath(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 = shortPath(mat, i + 1, j, x, y,                                   min_dist, dist + 1);     }     // go to the right cell     if (isSafe(mat, visited, i, j + 1)) {       min_dist = shortPath(mat, i, j + 1, x, y,                                   min_dist, dist + 1);     }     // go to the top cell     if (isSafe(mat, visited, i - 1, j)) {       min_dist = shortPath(mat, i - 1, j, x, y,                                   min_dist, dist + 1);     }     // go to the left cell     if (isSafe(mat, visited, i, j - 1)) {       min_dist = shortPath(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 shortPath() function   static int shortPathLength(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 = shortPath(mat, src[0], src[1],                             dest[0], dest[1], dist, 0);      if (dist != Integer.MAX_VALUE)       return dist;     return -1;   }     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 = shortPathLength(mat, src, dest);     System.out.print(dist);    } } 
Python
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 shortPath(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 = shortPath(             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 = shortPath(             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 = shortPath(             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 = shortPath(             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 shortPath() function def shortPathLength(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 = shortPath(mat, visited, src.first,                             src.second, dest.first, dest.second, dist, 0)      if (dist != sys.maxsize):         return dist     return -1  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 = shortPathLength(mat, src, dest)  print(dist) 
C#
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 shortPath(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 = shortPath(mat, i + 1, j, x, y,                                         min_dist, dist + 1);         }         // go to the right cell         if (isSafe(mat, visited, i, j + 1)) {             min_dist = shortPath(mat, i, j + 1, x, y,                                         min_dist, dist + 1);         }         // go to the top cell         if (isSafe(mat, visited, i - 1, j)) {             min_dist = shortPath(mat, i - 1, j, x, y,                                         min_dist, dist + 1);         }         // go to the left cell         if (isSafe(mat, visited, i, j - 1)) {             min_dist = shortPath(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 shortPath() function     static int shortPathLength(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 = shortPath(mat, src[0], src[1],                                 dest[0], dest[1], dist, 0);          if (dist != Int32.MaxValue)             return dist;         return -1;     }       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 = shortPathLength(mat, src, dest);                  Console.Write(dist);     } } 
JavaScript
// 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 shortPath(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             = shortPath(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             = shortPath(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             = shortPath(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             = shortPath(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 shortPath() function function shortPathLength(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 = shortPath(mat, visited, src.first,                             src.second, dest.first,                             dest.second, dist, 0);      if (dist != Number.MAX_SAFE_INTEGER)         return dist;     return -1; }  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 = shortPathLength(mat, src, dest); console.log(dist); 

Output
11

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

[Expected Approach] – Using BFS

The idea for this approach is inspired from Lee algorithm and uses BFS.  The BFS 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.
We start from the source cell and call the BFS while maintaining a queue to store the coordinates of the matrix, and a Boolean array to keep track of the visited cells.

C++
#include <bits/stdc++.h> using namespace std;  // A point in a Maze (Needed for QNode) struct Point {      int x, y;      Point(int x_, int y_) : x(x_), y(y_) {}  };  // A QNode (Needed for BFS) struct QNode {      Point p;      int d;      QNode(Point p_, int d_) : p(p_), d(d_) {}  };   bool isValid(int x, int y, int r, int c) {     return x >= 0 && x < r && y >= 0 && y < c; }  int BFS(vector<vector<int>>& mat, Point src, Point dest) {     int r = mat.size(), c = mat[0].size();          // If Source and Destination are valid     if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) return -1;      // Do BFS using Queue and Visited     vector<vector<bool>> vis(r, vector<bool>(c, false));     queue<QNode> q;     q.push(QNode(src, 0));     vis[src.x][src.y] = true;     while (!q.empty()) {                  // Pop an item from queue         QNode node = q.front(); q.pop();         Point p = node.p;         int d = node.d;          // If we reached the destination         if (p.x == dest.x && p.y == dest.y) return d;                  // Try all four adjacent         int dx[] = {-1, 0, 0, 1};         int dy[] = {0, -1, 1, 0};         for (int i = 0; i < 4; i++) {             int nx = p.x + dx[i], ny = p.y + dy[i];             if (isValid(nx, ny, r, c) && mat[nx][ny] && !vis[nx][ny]) {                 vis[nx][ny] = true;                 q.push(QNode(Point(nx, ny), d + 1));             }         }     }     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}     };      cout << BFS(mat, Point(0, 0), Point(3, 4)); } 
Java
// A point in a Maze (Needed for QNode) class Point {     int x, y;     Point(int x_, int y_) {         x = x_;         y = y_;     } }  // A QNode (Needed for BFS) class QNode {     Point p;     int d;     QNode(Point p_, int d_) {         p = p_;         d = d_;     } }  public class Maze {      static boolean isValid(int x, int y, int r, int c) {         return x >= 0 && x < r && y >= 0 && y < c;     }      static int BFS(int[][] mat, Point src, Point dest) {         int r = mat.length, c = mat[0].length;          // If Source and Destination are valid         if (mat[src.x][src.y] == 0 || mat[dest.x][dest.y] == 0) return -1;          // Do BFS using Queue and Visited         boolean[][] vis = new boolean[r][c];         java.util.Queue<QNode> q = new java.util.LinkedList<>();         q.add(new QNode(src, 0));         vis[src.x][src.y] = true;         while (!q.isEmpty()) {             // Pop an item from queue             QNode node = q.poll();             Point p = node.p;             int d = node.d;              // If we reached the destination             if (p.x == dest.x && p.y == dest.y) return d;              // Try all four adjacent             int[] dx = {-1, 0, 0, 1};             int[] dy = {0, -1, 1, 0};             for (int i = 0; i < 4; i++) {                 int nx = p.x + dx[i], ny = p.y + dy[i];                 if (isValid(nx, ny, r, c) && mat[nx][ny] == 1 && !vis[nx][ny]) {                     vis[nx][ny] = true;                     q.add(new QNode(new Point(nx, ny), d + 1));                 }             }         }         return -1;     }      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}         };          System.out.println(BFS(mat, new Point(0, 0), new Point(3, 4)));     } } 
Python
# A point in a Maze (Needed for QNode) class Point:     def __init__(self, x_, y_):         self.x = x_         self.y = y_  # A QNode (Needed for BFS) class QNode:     def __init__(self, p_, d_):         self.p = p_         self.d = d_   def is_valid(x, y, r, c):     return 0 <= x < r and 0 <= y < c   def bfs(mat, src, dest):     r, c = len(mat), len(mat[0])          # If Source and Destination are valid     if not mat[src.x][src.y] or not mat[dest.x][dest.y]: return -1      # Do BFS using Queue and Visited     vis = [[False] * c for _ in range(r)]     from collections import deque     q = deque([QNode(src, 0)])     vis[src.x][src.y] = True     while q:                  # Pop an item from queue         node = q.popleft()         p = node.p         d = node.d          # If we reached the destination         if p.x == dest.x and p.y == dest.y: return d                  # Try all four adjacent         dx = [-1, 0, 0, 1]         dy = [0, -1, 1, 0]         for i in range(4):             nx, ny = p.x + dx[i], p.y + dy[i]             if is_valid(nx, ny, r, c) and mat[nx][ny] and not vis[nx][ny]:                 vis[nx][ny] = True                 q.append(QNode(Point(nx, ny), d + 1))     return -1   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] ]  print(bfs(mat, Point(0, 0), Point(3, 4))) 
C#
// A point in a Maze (Needed for QNode) class Point {     public int x, y;     public Point(int x_, int y_) {         x = x_;         y = y_;     } }  // A QNode (Needed for BFS) class QNode {     public Point p;     public int d;     public QNode(Point p_, int d_) {         p = p_;         d = d_;     } }  public class Maze {      static bool IsValid(int x, int y, int r, int c) {         return x >= 0 && x < r && y >= 0 && y < c;     }      static int BFS(int[,] mat, Point src, Point dest) {         int r = mat.GetLength(0), c = mat.GetLength(1);          // If Source and Destination are valid         if (mat[src.x, src.y] == 0 || mat[dest.x, dest.y] == 0) return -1;          // Do BFS using Queue and Visited         bool[,] vis = new bool[r, c];         System.Collections.Generic.Queue<QNode> q = new System.Collections.Generic.Queue<QNode>();         q.Enqueue(new QNode(src, 0));         vis[src.x, src.y] = true;         while (q.Count > 0) {             // Pop an item from queue             QNode node = q.Dequeue();             Point p = node.p;             int d = node.d;              // If we reached the destination             if (p.x == dest.x && p.y == dest.y) return d;              // Try all four adjacent             int[] dx = {-1, 0, 0, 1};             int[] dy = {0, -1, 1, 0};             for (int i = 0; i < 4; i++) {                 int nx = p.x + dx[i], ny = p.y + dy[i];                 if (IsValid(nx, ny, r, c) && mat[nx, ny] == 1 && !vis[nx, ny]) {                     vis[nx, ny] = true;                     q.Enqueue(new QNode(new Point(nx, ny), d + 1));                 }             }         }         return -1;     }      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}         };          System.Console.WriteLine(BFS(mat, new Point(0, 0), new Point(3, 4)));     } } 
JavaScript
// A point in a Maze (Needed for QNode) class Point {     constructor(x_, y_) {         this.x = x_;         this.y = y_;     } }  // A QNode (Needed for BFS) class QNode {     constructor(p_, d_) {         this.p = p_;         this.d = d_;     } }  function isValid(x, y, r, c) {     return x >= 0 && x < r && y >= 0 && y < c; }  function BFS(mat, src, dest) {     const r = mat.length, c = mat[0].length;          // If Source and Destination are valid     if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) return -1;      // Do BFS using Queue and Visited     const vis = Array.from({ length: r }, () => Array(c).fill(false));     const queue = [new QNode(src, 0)];     vis[src.x][src.y] = true;     while (queue.length > 0) {         // Pop an item from queue         const node = queue.shift();         const p = node.p;         const d = node.d;          // If we reached the destination         if (p.x === dest.x && p.y === dest.y) return d;                  // Try all four adjacent         const dx = [-1, 0, 0, 1];         const dy = [0, -1, 1, 0];         for (let i = 0; i < 4; i++) {             const nx = p.x + dx[i], ny = p.y + dy[i];             if (isValid(nx, ny, r, c) && mat[nx][ny] && !vis[nx][ny]) {                 vis[nx][ny] = true;                 queue.push(new QNode(new Point(nx, ny), d + 1));             }         }     }     return -1; }  const 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] ];  console.log(BFS(mat, new Point(0, 0), new Point(3, 4))); 

Output
11

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



Next Article
Minimum cost to traverse from one index to another in the String

A

Aditya Goel
Improve
Article Tags :
  • DSA
  • Graph
  • Mathematical
  • Matrix
  • Amazon
  • BFS
  • DFS
  • Google
  • Samsung
  • Shortest Path
  • Zoho
Practice Tags :
  • Amazon
  • Google
  • Samsung
  • Zoho
  • BFS
  • DFS
  • Graph
  • Mathematical
  • Matrix
  • Shortest Path

Similar Reads

  • Breadth First Search or BFS for a Graph
    Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
    15+ min read
  • BFS in different language

    • C Program for Breadth First Search or BFS for a Graph
      The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree
      3 min read

    • Java Program for Breadth First Search or BFS for a Graph
      The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree
      3 min read

    • Breadth First Search or BFS for a Graph in Python
      Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent nodes. Once all adjacent are visited, then their adjacent are traversed. BFS is different from DFS in a way that closest vertices are visited before others. We mainly t
      4 min read

  • BFS for Disconnected Graph
    In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
    14 min read
  • Applications, Advantages and Disadvantages of Breadth First Search (BFS)
    We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
    4 min read
  • Breadth First Traversal ( BFS ) on a 2D array
    Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0,
    9 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,
    9 min read
  • Variations of BFS implementations

    • Implementation of BFS using adjacency matrix
      Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph. Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n
      7 min read

    • BFS using STL for competitive coding
      A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector.  In BFS, we start with a node. Create a queue and enqueue source into it. Mark source as visited.While queue is not empty, do followingDequeue a vertex from queue. Let t
      5 min read

    • Breadth First Search without using Queue
      Breadth-first search is a graph traversal algorithm which traverse a graph or tree level by level. In this article, BFS for a Graph is implemented using Adjacency list without using a Queue.Examples: Input: Output: BFS traversal = 2, 0, 3, 1 Explanation: In the following graph, we start traversal fr
      8 min read

    • BFS using vectors & queue as per the algorithm of CLRS
      Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm
      11 min read

    Easy problems on BFS

    • Find if there is a path between two vertices in a directed graph
      Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: T
      15 min read

    • Find if there is a path between two vertices in an undirected graph
      Given an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print "Yes" if a path exists and "No" otherwise. Examples: U = 1, V = 2 Output: No Explanation: There is no edge between the two points and
      15+ min read

    • Print all the levels with odd and even number of nodes in it | Set-2
      Given an N-ary tree, print all the levels with odd and even number of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2 No
      12 min read

    • Finding the path from one vertex to rest using BFS
      Given an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS. Examples: Input: Output: 0 <- 2 1 <- 0 <- 2 2 3 <- 1 <- 0 <- 2 4 <- 5 <- 2 5 <- 2 6 <- 2 Approach: In the images shown below:
      14 min read

    • Find all reachable nodes from every node present in a given set
      Given an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set. Consider below undirected graph with 2 disconnected components.    arr[] = {1 , 2 , 5}Reachable nodes from 1 are 1, 2, 3, 4Reachable nodes from 2 are 1, 2, 3, 4Reachable nodes from 5
      12 min read

    • Program to print all the non-reachable nodes | Using BFS
      Given an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search. For example: Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2
      8 min read

    • Check whether a given graph is Bipartite or not
      Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not. Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex
      9 min read

    • Print all paths from a given source to a destination using BFS
      Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’. Please note that in the cases, we have cycles in the graph, we need not to consider paths have cycles as in case of cycles, there can by infinitely many by doing multiple iteratio
      9 min read

    • Minimum steps to reach target by a Knight | Set 1
      Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position. Examples: Input: knightPosition: (1, 3) , targetPosition: (5, 0) Output: 3Explanation: In above diagram K
      9 min read

    Intermediate problems on BFS

    • Traversal of a Graph in lexicographical order using BFS
      C/C++ Code // C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map<char, set<char> >& G, char S, map<char, bool>& vis) { // Stores nodes of
      9 min read

    • Detect cycle in an undirected graph using BFS
      Given an undirected graph, the task is to determine if cycle is present in it or not. Examples: Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0. Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: fals
      6 min read

    • Detect Cycle in a Directed Graph using BFS
      Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return
      11 min read

    • Minimum number of edges between two vertices of a Graph
      You are given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). Examples: Input: For given graph G. Find minimum number of edges between (1, 5). Output: 2Explanation: (1, 2) and (2, 5) are the only edges resu
      8 min read

    • Word Ladder - Shortest Chain To Reach Target Word
      Given an array of strings arr[], and two different strings start and target, representing two words. The task is to find the length of the smallest chain from string start to target, such that only one character of the adjacent words differs and each word exists in arr[]. Note: Print 0 if it is not
      15 min read

    • Print the lexicographically smallest BFS of the graph starting from 1
      Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1. Note: The vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3
      7 min read

    • Shortest path in an unweighted graph
      Given an unweighted, undirected graph of V nodes and E edges, a source node S, and a destination node D, we need to find the shortest path from node S to node D in the graph. Input: V = 8, E = 10, S = 0, D = 7, edges[][] = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {4, 7}, {3, 7}, {6, 7}, {4, 5}, {4, 6}, {5,
      11 min read

    • Number of shortest paths in an unweighted and directed graph
      Given an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shorte
      11 min read

    • Distance of nearest cell having 1 in a binary matrix
      Given a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.The distance is calculated as |i1  - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1. Th
      15+ min read

    Hard Problems on BFS

    • Islands in a graph using BFS
      Given an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
      15+ min read

    • Print all shortest paths between given source and destination in an undirected graph
      Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 ->
      13 min read

    • Count Number of Ways to Reach Destination in a Maze using BFS
      Given a maze of dimensions n x m represented by the matrix mat, where mat[i][j] = -1 represents a blocked cell and mat[i][j] = 0 represents an unblocked cell, the task is to count the number of ways to reach the bottom-right cell starting from the top-left cell by moving right (i, j+1) or down (i+1,
      8 min read

    • Coin Change | BFS Approach
      Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4}
      6 min read

    • Water Jug problem using BFS
      Given two empty jugs of m and n litres respectively. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water. The task is to find the minimum number of operations to be performed to obtain d litres of water in one of the jugs. In case
      12 min read

    • Word Ladder - Set 2 ( Bi-directional BFS )
      Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may b
      15+ min read

    • Implementing Water Supply Problem using Breadth First Search
      Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are b
      10 min read

    • Minimum Cost Path in a directed graph via given set of intermediate nodes
      Given a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D. Examples: Input: V = {7}, S = 0, D = 6 Output: 11 Explanation: Minimum path 0->7->5->6.
      10 min read

    • Shortest path in a Binary Maze
      Given an M x N 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. Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, an
      15+ min read

    • Minimum cost to traverse from one index to another in the String
      Given a string S of length N consisting of lower case character, the task is to find the minimum cost to reach from index i to index j. At any index k, the cost to jump to the index k+1 and k-1(without going out of bounds) is 1. Additionally, the cost to jump to any index m such that S[m] = S[k] is
      10 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences