Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- TASK: AG_Run Loop Peatt
- LANG: CPP
- AUTHOR: PeaTT~
- SOLUTION: BFS + Greedy
- */
- #include<bits/stdc++.h>
- using namespace std;
- int di[]={+1,0,+0,-1},dj[]={+0,-1,+1,+0},dist[1010][1010];
- char grid[1010][1010];
- queue< pair<int, int> > bfs;
- void play(){
- int r,c,a,si,sj,ii,jj,i,j;
- cin>>r>>c>>a;
- for(int i=0;i<r;i++){
- for(int j=0;j<c;j++){
- cin>>grid[i][j];
- if(grid[i][j]=='P')
- si=i,sj=j;
- }
- }
- if(a%2==1){
- cout<<"Can\'t do"<<endl;
- return ;
- }
- bfs.push({si,sj});
- memset(dist,-1,sizeof dist);
- dist[si][sj] = 0;
- while( !bfs.empty() ){ //BFS find dist from P
- i = bfs.front().first, j= bfs.front().second;
- bfs.pop();
- for(int k=0;k<4;k++){
- ii = i+di[k], jj=j+dj[k];
- if(ii<0||jj<0||ii>=r||jj>=c) continue;
- if(grid[ii][jj]=='#') continue;
- if(dist[ii][jj]!=-1) continue;
- dist[ii][jj] = dist[i][j] + 1;
- bfs.push({ii,jj});
- }
- }
- int left = a/2;
- vector<int> ans;
- i = si, j = sj;
- while(left--){
- for(int k=0;k<4;k++){ //Greedy choose
- ii = i+di[k], jj = j+dj[k];
- if(ii<0||jj<0||ii>=r||jj>=c) continue;
- if(grid[ii][jj]=='#') continue;
- if(dist[ii][jj]>a/2) continue; //Checking for valid move
- ans.push_back(k);
- i = ii, j= jj;
- break;
- }
- }
- if(ans.size()==a/2){
- for(auto x: ans){
- if(x==0) cout<<"D";
- else if(x==1) cout<<"L";
- else if(x==2) cout<<"R";
- else if(x==3) cout<<"U";
- }
- reverse(ans.begin(),ans.end());
- for(auto x: ans){
- if(x==3) cout<<"D";
- else if(x==2) cout<<"L";
- else if(x==1) cout<<"R";
- else if(x==0) cout<<"U";
- }
- cout<<endl;
- }
- else
- cout<<"Can\'t do"<<endl;
- }
- int main(){
- ios_base::sync_with_stdio(NULL);
- cin.tie(NULL);
- cout.tie(NULL);
- int q;
- cin >> q;
- while(q--)
- play();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment