Samkit5025

Untitled

Jun 18th, 2022
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int minimumRoom(int N,int M,vector<vector<int>> &A){
  5.  
  6. vector<vector<int>> dist(N,vector<int>(M,10000000));
  7. vector<vector<bool>> visited(N,vector<bool>(M,false));
  8.  
  9. queue<pair<int,int>> q;
  10. q.push({0,0});
  11. dist[0][0] = 1;
  12. visited[0][0] = true;
  13.  
  14. while(!q.empty()){
  15. auto curr = q.front();
  16. q.pop();
  17.  
  18. int i = curr.first;
  19. int j = curr.second;
  20.  
  21. if(i+1<N && visited[i+1][j] == false && A[i+1][j]!=A[i][j]){
  22. dist[i+1][j] = dist[i][j]+1;
  23. visited[i+1][j] = true;
  24. q.push({i+1,j});
  25. }
  26. if(j+1<M && visited[i][j+1] == false && A[i][j+1]!=A[i][j]){
  27. dist[i][j+1] = dist[i][j]+1;
  28. visited[i][j+1] = true;
  29. q.push({i,j+1});
  30. }
  31. if(i-1>=0 && visited[i-1][j] == false && A[i-1][j]!=A[i][j]){
  32. dist[i-1][j] = dist[i][j]+1;
  33. visited[i-1][j] = true;
  34. q.push({i-1,j});
  35. }
  36. if(j-1>=0 && visited[i][j-1] == false && A[i][j-1]!=A[i][j]){
  37. dist[i][j-1] = dist[i][j]+1;
  38. visited[i][j-1] = true;
  39. q.push({i,j-1});
  40. }
  41. }
  42.  
  43. if(visited[N-1][M-1]){
  44. return dist[N-1][M-1];
  45. }
  46.  
  47. return -1;
  48. }
  49.  
  50. int main()
  51. {
  52. int N,M;
  53. cin>>N>>M;
  54.  
  55. vector<vector<int>> A(N,vector<int>(M));
  56.  
  57. for(int i=0;i<N;i++){
  58. for(int j=0;j<M;j++){
  59. cin>>A[i][j];
  60. }
  61. }
  62.  
  63. cout<<minimumRoom(N,M,A)<<endl;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment