jayati

Shortest Source to Destination Path

Dec 7th, 2023
749
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // Initial Template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. // } Driver Code Ends
  8. // User function Template for C++
  9.  
  10. class Solution {
  11.   public:
  12.     int shortestDistance(int N, int M, vector<vector<int>> A, int X, int Y) {
  13.        
  14.         // code here
  15.         if(A[0][0]!=1)
  16.         {
  17.             return -1;
  18.         }
  19.         queue<pair<int,int>> q;
  20.         int drow[4]={-1,0,1,0};
  21.         int dcol[4]={0,-1,0,1};
  22.        
  23.         vector<vector<int>> dist(N,vector<int>(M,INT_MAX));
  24.        
  25.         q.push({0,0});
  26.         dist[0][0]=0;
  27.         while(!q.empty())
  28.         {
  29.             auto it = q.front();
  30.             q.pop();
  31.            
  32.             int r = it.first;
  33.             int c = it.second;
  34.            
  35.             if(r==X && c==Y)
  36.             {
  37.                 return dist[r][c];
  38.             }
  39.             for(int i=0;i<4;i++)
  40.             {
  41.                 int nr = r+ drow[i];
  42.                 int nc = c+ dcol[i];
  43.                 if(nr >=0 && nr<N && nc>=0 && nc<M && A[nr][nc]!=0)
  44.                 {
  45.                     if(dist[nr][nc] > 1+dist[r][c])
  46.                     {
  47.                         dist[nr][nc] = 1+dist[r][c];
  48.                         q.push({nr,nc});
  49.                     }
  50.                 }
  51.             }
  52.         }
  53.         return -1;
  54.        
  55.     }
  56. };
  57.  
  58. //{ Driver Code Starts.
  59. int main() {
  60.     int t;
  61.     cin >> t;
  62.     while (t--) {
  63.         int N, M, x, y;
  64.         cin >> N >> M;
  65.         vector<vector<int>> v(N, vector<int>(M));
  66.         for (int i = 0; i < N; i++)
  67.             for (int j = 0; j < M; j++) cin >> v[i][j];
  68.         cin >> x >> y;
  69.         Solution ob;
  70.         cout << ob.shortestDistance(N, M, v, x, y) << "\n";
  71.     }
  72. }
  73. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment