We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
voidprintShortestPath(intn,inti_start,intj_start,inti_end,intj_end){std::vector<std::tuple<int,int,std::string>>direct={{-2,-1,"UL"},{-2,1,"UR"},{0,2,"R"},{2,1,"LR"},{2,-1,"LL"},{0,-2,"L"}};// Print the distance along with the sequence of moves.queue<std::tuple<int,int,std::string>>pq;vector<vector<bool>>vis(n,vector<bool>(n,false));vis[i_start][j_start]=true;// add start pointintsteps=0;pq.emplace(i_start,j_start,string(""));intstep=0;while(!pq.empty()){intsize=pq.size();steps++;while(size--){auto[r,c,path]=pq.front();pq.pop();// reach target nodeif(r==i_end&&c==j_end){cout<<steps-1<<endl;cout<<path<<endl;return;}for(constauto&[nb_r,nb_c,name]:direct){intnew_r=r+nb_r;intnew_c=c+nb_c;// validate nodeif(new_r>=0&&new_r<n&&new_c>=0&&new_c<n&&!vis[new_r][new_c]){vis[new_r][new_c]=true;pq.emplace(new_r,new_c,path+name+" ");}}}}// not found any pathcout<<"Impossible"<<endl;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Red Knight's Shortest Path
You are viewing a single comment's thread. Return to all comments →
C++ BFS solution