# """# This is GridMaster's API interface.# You should not implement it, or speculate about its implementation# """# class GridMaster(object):# def canMove(self, direction: str) -> bool:### def move(self, direction: str) -> bool:### def isTarget(self) -> None:##classSolution(object):deffindShortestPath(self,master:"GridMaster")->int:defdfs(i:int,j:int):ifmaster.isTarget():nonlocaltargettarget=(i,j)returnfork,cinenumerate(s):x,y=i+dirs[k],j+dirs[k+1]ifmaster.canMove(c)and(x,y)notinvis:vis.add((x,y))master.move(c)dfs(x,y)master.move(s[(k+2)%4])s="URDL"dirs=(-1,0,1,0,-1)target=Nonevis=set()dfs(0,0)iftargetisNone:return-1vis.discard((0,0))q=deque([(0,0)])ans=-1whileq:ans+=1for_inrange(len(q)):i,j=q.popleft()if(i,j)==target:returnansfora,binpairwise(dirs):x,y=i+a,j+bif(x,y)invis:vis.remove((x,y))q.append((x,y))return-1
/** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { * boolean canMove(char direction); * void move(char direction); * boolean isTarget(); * } */classSolution{privateint[]target;privateGridMastermaster;privatefinalintn=2010;privatefinalStrings="URDL";privatefinalint[]dirs={-1,0,1,0,-1};privatefinalSet<Integer>vis=newHashSet<>();publicintfindShortestPath(GridMastermaster){this.master=master;dfs(0,0);if(target==null){return-1;}vis.remove(0);Deque<int[]>q=newArrayDeque<>();q.offer(newint[]{0,0});for(intans=0;!q.isEmpty();++ans){for(intm=q.size();m>0;--m){varp=q.poll();if(p[0]==target[0]&&p[1]==target[1]){returnans;}for(intk=0;k<4;++k){intx=p[0]+dirs[k],y=p[1]+dirs[k+1];if(vis.remove(x*n+y)){q.offer(newint[]{x,y});}}}}return-1;}privatevoiddfs(inti,intj){if(master.isTarget()){target=newint[]{i,j};return;}for(intk=0;k<4;++k){intx=i+dirs[k],y=j+dirs[k+1];if(master.canMove(s.charAt(k))&&vis.add(x*n+y)){master.move(s.charAt(k));dfs(x,y);master.move(s.charAt((k+2)%4));}}}}
/** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { * public: * bool canMove(char direction); * void move(char direction); * boolean isTarget(); * }; */classSolution{private:constintn=2010;intdirs[5]={-1,0,1,0,-1};strings="URDL";inttarget;unordered_set<int>vis;public:intfindShortestPath(GridMaster&master){target=n*n;vis.insert(0);dfs(0,0,master);if(target==n*n){return-1;}vis.erase(0);queue<pair<int,int>>q;q.emplace(0,0);for(intans=0;q.size();++ans){for(intm=q.size();m;--m){auto[i,j]=q.front();q.pop();if(i*n+j==target){returnans;}for(intk=0;k<4;++k){intx=i+dirs[k],y=j+dirs[k+1];if(vis.count(x*n+y)){vis.erase(x*n+y);q.emplace(x,y);}}}}return-1;}voiddfs(inti,intj,GridMaster&master){if(master.isTarget()){target=i*n+j;}for(intk=0;k<4;++k){intx=i+dirs[k],y=j+dirs[k+1];if(master.canMove(s[k])&&!vis.count(x*n+y)){vis.insert(x*n+y);master.move(s[k]);dfs(x,y,master);master.move(s[(k+2)%4]);}}}};