dvjsharma

Untitled

Aug 21st, 2025
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct State {
  5. int x, y, removed, dist;
  6. };
  7.  
  8. int shortestPathWithRemovals(vector<vector<int>>& grid, int k) {
  9. int n = grid.size(), m = grid[0].size();
  10. vector<vector<vector<bool>>> visited(n, vector<vector<bool>>(m, vector<bool>(k + 1, false)));
  11.  
  12. queue<State> q;
  13. q.push({0, 0, 0, 0});
  14. visited[0][0][0] = true;
  15.  
  16. int dx[4] = {1, -1, 0, 0};
  17. int dy[4] = {0, 0, 1, -1};
  18.  
  19. while (!q.empty()) {
  20. auto [x, y, removed, dist] = q.front();
  21. q.pop();
  22.  
  23. if (x == n - 1 && y == m - 1) return dist;
  24.  
  25. for (int d = 0; d < 4; d++) {
  26. int nx = x + dx[d], ny = y + dy[d];
  27.  
  28. if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
  29.  
  30. int newRemoved = removed + grid[nx][ny]; // remove wall if present
  31. if (newRemoved <= k && !visited[nx][ny][newRemoved]) {
  32. visited[nx][ny][newRemoved] = true;
  33. q.push({nx, ny, newRemoved, dist + 1});
  34. }
  35. }
  36. }
  37. return -1; // no path
  38. }
  39.  
  40. int main() {
  41. vector<vector<int>> grid = {
  42. {0, 1, 0, 0, 0},
  43. {0, 1, 0, 1, 0},
  44. {0, 0, 0, 1, 0},
  45. {1, 1, 1, 1, 0},
  46. {0, 0, 0, 0, 0}
  47. };
  48. int k = 1; // allow removal of 1 wall
  49.  
  50. cout << shortestPathWithRemovals(grid, k) << endl;
  51. return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment