Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int minimumRoom(int N,int M,vector<vector<int>> &A){
- vector<vector<int>> dist(N,vector<int>(M,10000000));
- vector<vector<bool>> visited(N,vector<bool>(M,false));
- queue<pair<int,int>> q;
- q.push({0,0});
- dist[0][0] = 1;
- visited[0][0] = true;
- while(!q.empty()){
- auto curr = q.front();
- q.pop();
- int i = curr.first;
- int j = curr.second;
- if(i+1<N && visited[i+1][j] == false && A[i+1][j]!=A[i][j]){
- dist[i+1][j] = dist[i][j]+1;
- visited[i+1][j] = true;
- q.push({i+1,j});
- }
- if(j+1<M && visited[i][j+1] == false && A[i][j+1]!=A[i][j]){
- dist[i][j+1] = dist[i][j]+1;
- visited[i][j+1] = true;
- q.push({i,j+1});
- }
- if(i-1>=0 && visited[i-1][j] == false && A[i-1][j]!=A[i][j]){
- dist[i-1][j] = dist[i][j]+1;
- visited[i-1][j] = true;
- q.push({i-1,j});
- }
- if(j-1>=0 && visited[i][j-1] == false && A[i][j-1]!=A[i][j]){
- dist[i][j-1] = dist[i][j]+1;
- visited[i][j-1] = true;
- q.push({i,j-1});
- }
- }
- if(visited[N-1][M-1]){
- return dist[N-1][M-1];
- }
- return -1;
- }
- int main()
- {
- int N,M;
- cin>>N>>M;
- vector<vector<int>> A(N,vector<int>(M));
- for(int i=0;i<N;i++){
- for(int j=0;j<M;j++){
- cin>>A[i][j];
- }
- }
- cout<<minimumRoom(N,M,A)<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment