Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- int min1,n,m;
- char A[51][51]; // for storing the matrix
- bool B[51][51]; //to keep track which cell is visted (a cell will be set to true when visited)
- void coins(int i,int j,int k,int count,int steps)
- {
- if(steps >k || count>=min1) //Case when the chosen path takes more time than k
- {
- return;
- }
- else if(A[i][j]=='*') // when goal is found
- {
- if(count<min1)
- min1=count;
- return;
- }
- else if(B[i][j]==true) // when a cell is found which has already been visited(in case of cycles)
- return;
- else // this else part tries to get all possible paths for a cell A[i][j]
- {
- if(A[i][j]=='U')
- {
- B[i][j]=true;
- if((i-1)>=0)
- coins(i-1,j,k,count,steps+1);
- if((j-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='L';
- coins(i,j-1,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((i+1)<n)
- {
- char old=A[i][j];
- A[i][j]='D';
- coins(i+1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((j+1)<m)
- {
- char old=A[i][j];
- A[i][j]='R';
- coins(i,j+1,k,count+1,steps+1);
- A[i][j]=old;
- }
- B[i][j]=false;
- }
- else if(A[i][j]=='L')
- {
- B[i][j]=true;
- if((j-1)>=0)
- coins(i,j-1,k,count,steps+1);
- if((i-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='U';
- coins(i-1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((i+1)<n)
- {
- char old=A[i][j];
- A[i][j]='D';
- coins(i+1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((j+1)<m)
- {
- char old=A[i][j];
- A[i][j]='R';
- coins(i,j+1,k,count+1,steps+1);
- A[i][j]=old;
- }
- B[i][j]=false;
- }
- else if(A[i][j]=='D')
- {
- B[i][j]=true;
- if((i+1)<n)
- coins(i+1,j,k,count,steps+1);
- if((i-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='U';
- coins(i-1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((j-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='L';
- coins(i,j-1,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((j+1)<m)
- {
- char old=A[i][j];
- A[i][j]='R';
- coins(i,j+1,k,count+1,steps+1);
- A[i][j]=old;
- }
- B[i][j]=false;
- }
- else if(A[i][j]=='R')
- {
- B[i][j]=true;
- if((j+1)<m)
- coins(i,j+1,k,count,steps+1);
- if((i-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='U';
- coins(i-1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((j-1)>=0)
- {
- char old=A[i][j];
- A[i][j]='L';
- coins(i,j-1,k,count+1,steps+1);
- A[i][j]=old;
- }
- if((i+1)<n)
- {
- char old=A[i][j];
- A[i][j]='D';
- coins(i+1,j,k,count+1,steps+1);
- A[i][j]=old;
- }
- B[i][j]=false;
- }
- }
- }
- int main()
- {
- int k,i,j;
- cin>>n>>m>>k;
- for(i=0;i<n;++i)
- for(j=0;j<m;++j)
- cin>>A[i][j];
- min1=1000000000;
- coins(0,0,k,0,0);
- if(min1==1000000000)
- cout<<-1;
- else
- cout<<min1;
- }
Add Comment
Please, Sign In to add comment