classSolution{public:stringfindShortestWay(vector<vector<int>>&maze,vector<int>&ball,vector<int>&hole){stringans="impossible";dfs(maze,ball[0],ball[1],hole,0,0,0,INT_MAX,"",ans);returnans;}private:voiddfs(vector<vector<int>>&maze,inti,intj,constvector<int>&hole,intdx,intdy,intsteps,int&&minSteps,string&&path,string&ans){if(steps>=minSteps)return;if(dx!=0||dy!=0){// Both are zero for the initial ball positionwhile(i+dx>=0&&i+dx<maze.size()&&j+dy>=0&&j+dy<maze[0].size()&&maze[i+dx][j+dy]!=1){i+=dx;j+=dy;++steps;if(i==hole[0]&&j==hole[1]&&steps<minSteps){minSteps=steps;ans=path;}}}if(maze[i][j]==0||steps+2<maze[i][j]){maze[i][j]=steps+2;// +2 to because of maze[i][j] == 0 || 1if(dx==0)dfs(maze,i,j,hole,1,0,steps,move(minSteps),path+"d",ans);if(dy==0)dfs(maze,i,j,hole,0,-1,steps,move(minSteps),path+"l",ans);if(dy==0)dfs(maze,i,j,hole,0,1,steps,move(minSteps),path+"r",ans);if(dx==0)dfs(maze,i,j,hole,-1,0,steps,move(minSteps),path+"u",ans);}}};
classSolution{publicStringfindShortestWay(int[][]maze,int[]ball,int[]hole){dfs(maze,ball[0],ball[1],hole,0,0,0,"");returnans;}privateStringans="impossible";privateintminSteps=Integer.MAX_VALUE;privatevoiddfs(int[][]maze,inti,intj,int[]hole,intdx,intdy,intsteps,finalStringpath){if(steps>=minSteps)return;if(dx!=0||dy!=0){// Both are zero for the initial ball positionwhile(i+dx>=0&&i+dx<maze.length&&j+dy>=0&&j+dy<maze[0].length&&maze[i+dx][j+dy]!=1){i+=dx;j+=dy;++steps;if(i==hole[0]&&j==hole[1]&&steps<minSteps){minSteps=steps;ans=path;}}}if(maze[i][j]==0||steps+2<maze[i][j]){maze[i][j]=steps+2;// +2 to because of maze[i][j] == 0 || 1if(dx==0)dfs(maze,i,j,hole,1,0,steps,path+"d");if(dy==0)dfs(maze,i,j,hole,0,-1,steps,path+"l");if(dy==0)dfs(maze,i,j,hole,0,1,steps,path+"r");if(dx==0)dfs(maze,i,j,hole,-1,0,steps,path+"u");}}}
classSolution:deffindShortestWay(self,maze:List[List[int]],ball:List[int],hole:List[int])->str:ans="impossible"minSteps=math.infdefdfs(i:int,j:int,dx:int,dy:int,steps:int,path:str):nonlocalansnonlocalminStepsifsteps>=minSteps:returnifdx!=0ordy!=0:# Both are zero for the initial ball positionwhile0<=i+dx<len(maze)and0<=j+dy<len(maze[0]) \
andmaze[i+dx][j+dy]!=1:i+=dxj+=dysteps+=1ifi==hole[0]andj==hole[1]andsteps<minSteps:minSteps=stepsans=pathifmaze[i][j]==0orsteps+2<maze[i][j]:maze[i][j]=steps+2# +2 to because of maze[i][j] == 0 || 1ifdx==0:dfs(i,j,1,0,steps,path+'d')ifdy==0:dfs(i,j,0,-1,steps,path+'l')ifdy==0:dfs(i,j,0,1,steps,path+'r')ifdx==0:dfs(i,j,-1,0,steps,path+'u')dfs(ball[0],ball[1],0,0,0,'')returnans