# """# 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) -> int:### def isTarget(self) -> None:##classSolution(object):deffindShortestPath(self,master:'GridMaster')->int:defdfs(i,j):nonlocaltargetifmaster.isTarget():target=(i,j)fordir,(a,b,ndir)indirs.items():x,y=i+a,j+bif0<=x<Nand0<=y<Nandmaster.canMove(dir)andg[x][y]==-1:g[x][y]=master.move(dir)dfs(x,y)master.move(ndir)target=(-1,-1)N=200INF=0x3F3F3F3Fg=[[-1]*Nfor_inrange(N)]dirs={'U':(-1,0,'D'),'D':(1,0,'U'),'L':(0,-1,'R'),'R':(0,1,'L'),}dfs(100,100)iftarget==(-1,-1):return-1q=[(0,100,100)]dist=[[INF]*Nfor_inrange(N)]dist[100][100]=0whileq:w,i,j=heappop(q)if(i,j)==target:returnwfora,b,_indirs.values():x,y=i+a,j+bif(0<=x<Nand0<=y<Nandg[x][y]!=-1anddist[x][y]>w+g[x][y]):dist[x][y]=w+g[x][y]heappush(q,(dist[x][y],x,y))return0
/** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { * boolean canMove(char direction); * int move(char direction); * boolean isTarget(); * } */classSolution{privatestaticfinalchar[]dir={'U','R','D','L'};privatestaticfinalchar[]ndir={'D','L','U','R'};privatestaticfinalint[]dirs={-1,0,1,0,-1};privatestaticfinalintN=200;privatestaticfinalintINF=0x3f3f3f3f;privatestaticint[][]g=newint[N][N];privatestaticint[][]dist=newint[N][N];privateint[]target;publicintfindShortestPath(GridMastermaster){target=newint[]{-1,-1};for(inti=0;i<N;++i){Arrays.fill(g[i],-1);Arrays.fill(dist[i],INF);}dfs(100,100,master);if(target[0]==-1&&target[1]==-1){return-1;}PriorityQueue<int[]>q=newPriorityQueue<>(Comparator.comparingInt(a->a[0]));q.offer(newint[]{0,100,100});dist[100][100]=0;while(!q.isEmpty()){int[]p=q.poll();intw=p[0],i=p[1],j=p[2];if(i==target[0]&&j==target[1]){returnw;}for(intk=0;k<4;++k){intx=i+dirs[k],y=j+dirs[k+1];if(x>=0&&x<N&&y>=0&&y<N&&g[x][y]!=-1&&dist[x][y]>w+g[x][y]){dist[x][y]=w+g[x][y];q.offer(newint[]{dist[x][y],x,y});}}}return0;}privatevoiddfs(inti,intj,GridMastermaster){if(master.isTarget()){target=newint[]{i,j};}for(intk=0;k<4;++k){chard=dir[k],nd=ndir[k];intx=i+dirs[k],y=j+dirs[k+1];if(x>=0&&x<N&&y>=0&&y<N&&master.canMove(d)&&g[x][y]==-1){g[x][y]=master.move(d);dfs(x,y,master);master.move(nd);}}}}