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.
staticconstsize_trodsCount=4;staticconstsize_tstatesMaxCount=static_cast<size_t>(std::pow(4,10));size_thanoi(std::vector<size_t>const&positions){usingnamespacestd;usingstate_t=vector<size_t>;usingmask_t=vector<bool>;autoconst&disksCount{positions.size()};// last element of a vector tracks how many moves done to achive its stateautostateAtTreeRoot(state_t(disksCount+1,0));transform(cbegin(positions),cend(positions),begin(stateAtTreeRoot),[&](constauto&disk){returndisk-1;});autobfsQ{queue<state_t>{}};bfsQ.push(stateAtTreeRoot);autostatesAtTreeVisited{mask_t(::statesMaxCount,false)};autohash=[&](autoconst&value){size_thashValue{0};for_each(cbegin(value),cend(value)-1,[&](autoconst&num){hashValue=hashValue*::rodsCount+num;});returnhashValue;};statesAtTreeVisited.at(hash(stateAtTreeRoot))=true;autorodsVisitedToMoveFrom{mask_t(::rodsCount,false)};autorodsVisitedToMoveTo{mask_t(::rodsCount,false)};size_thashValue{0};autostateAtSubTreeRoot{state_t(disksCount+1,0)};autostateAtNextNode{state_t(disksCount+1,0)};while(!bfsQ.empty()){copy(cbegin(bfsQ.front()),cend(bfsQ.front()),begin(stateAtSubTreeRoot));bfsQ.pop();for(size_tdisk{0};disk<disksCount;++disk){if(rodsVisitedToMoveFrom.at(stateAtSubTreeRoot.at(disk))){continue;}rodsVisitedToMoveFrom.at(stateAtSubTreeRoot.at(disk))=true;copy(cbegin(rodsVisitedToMoveFrom),cend(rodsVisitedToMoveFrom),begin(rodsVisitedToMoveTo));for(size_tnewRod{0};newRod<::rodsCount;++newRod){if(rodsVisitedToMoveTo.at(newRod)){continue;}rodsVisitedToMoveTo.at(newRod)=true;copy(cbegin(stateAtSubTreeRoot),cend(stateAtSubTreeRoot),begin(stateAtNextNode));++stateAtNextNode.back();stateAtNextNode.at(disk)=newRod;hashValue=hash(stateAtNextNode);if(hashValue==0){returnstateAtNextNode.back();}if(statesAtTreeVisited.at(hashValue)){continue;}statesAtTreeVisited.at(hashValue)=true;bfsQ.push(stateAtNextNode);}fill(begin(rodsVisitedToMoveTo),end(rodsVisitedToMoveTo),false);}fill(begin(rodsVisitedToMoveFrom),end(rodsVisitedToMoveFrom),false);}returnnumeric_limits<size_t>::max();}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Gena Playing Hanoi
You are viewing a single comment's thread. Return to all comments →
C++ (more at https://github.com/IhorVodko/Hackerrank_solutions , feel free to give a star:) )
Build bfs tree where each node is a game state.