-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest_distance_in_binary_maze.cpp
57 lines (42 loc) · 1.56 KB
/
shortest_distance_in_binary_maze.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<vector>
#include<queue>
#include<limits.h>
using namespace std;
// problem link -> https://www.geeksforgeeks.org/problems/shortest-path-in-a-binary-maze-1655453161/1
int delrow[4] = {-1,0,1,0};
int delcol[4] = {0,1,0,-1};
int shortestPath(vector<vector<int>> &grid, pair<int, int> source,
pair<int, int> destination) {
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> distance(n, vector<int>(m, INT_MAX));
distance[source.first][source.second] = 0;
queue<pair<int,int>> q;
q.push({source.first, source.second});
while(!q.empty())
{
int row = q.front().first;
int col = q.front().second;
q.pop();
for(int i = 0; i<4; i++)
{
int nrow = delrow[i] + row;
int ncol = delcol[i] + col;
if(nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && grid[nrow][ncol] == 1)
{
if(distance[nrow][ncol] > distance[row][col] + 1)
{
distance[nrow][ncol] = distance[row][col] + 1;
q.push({nrow,ncol});
}
}
}
}
if(distance[destination.first][destination.second] == INT_MAX) return -1;
return distance[destination.first][destination.second];
}
int main()
{
return 0;
}