nikunjsoni

490

May 3rd, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
  4.         int m = maze.size(), n = maze[0].size(), d[] = {0, 1, 0, -1, 0};
  5.         queue<vector<int>> q;
  6.         q.push(start);
  7.         maze[start[0]][start[1]] = -1;
  8.         while(!q.empty()){
  9.             vector<int> p = q.front();
  10.             q.pop();
  11.             for(int i = 0; i < 4; i++) {
  12.                 int r = p[0], c = p[1];
  13.                 while(r + d[i] >= 0 && r + d[i] < m && c + d[i + 1] >= 0 && c + d[i + 1] < n && maze[r + d[i]][c + d[i + 1]] <= 0) {
  14.                     r += d[i];
  15.                     c += d[i + 1];
  16.                 }
  17.                 if(r == destination[0] && c == destination[1]) {
  18.                     return true;
  19.                 }
  20.                 if(!maze[r][c]) {
  21.                     maze[r][c] = -1;
  22.                     q.push({r, c});
  23.                 }
  24.             }
  25.         }
  26.         return false;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment