The main idea is: to give you a ball, just at the beginning is still, you can touch to give him a first speed, once the ball movement will not stop, unless encountered a stone. After encountering the stone, the ball stopped in place and the stone was smashed. The ball crosses the border even if it fails. Ask you at least how many times you can get the ball to the finish line. There is a requirement in the title, if more than 10 steps, even if the failure.
This problem has been doing for a long time. Maybe the method is too troublesome.
#include <stdio.h>
#include <string.h>
int map[105][105],si,sj,ei,ej,w,h; 1 Right 2 down 3 Left 4 up
int Flag,t,dir[4][2]={0,1,1,0,0,-1,-1,0},mini;
int check (int x,int y)
{
if (x<=0| | y<=0| | x>h| | Y>W) return 0;
return 1;
}
void Dfs (int x,int y,int cnt,int turn,int speed)//x,y represents the coordinates of the ball, CNT represents the current number of operations, turn represents the direction, speed determines the ball State
{
if (check (x, y) ==0) {Flag=1;return;} Determine whether or not to cross.
if (X==ei&&y==ej) {
if (mini>cnt) mini=cnt;
Flag=1;t=cnt;return;
}
if (cnt>10) return;
if (speed==0) {//If the ball is stationary, search in 4 directions.
for (int i=0;i<4;i++)
{
int fx=x+dir[i][0];
int fy=y+dir[i][1];
if (map[fx][fy]==1)If you're surrounded by rocks, skip.
Continue
DFS (fx,fy,cnt+1,i+1,1);
}
}
else {//If the ball is moving, search in the original direction
if (turn==1)
{
if (map[x][y+1]==1)
{
map[x][y+1]=0;
DFS (x,y,cnt,1,0);
Map[x][y+1]=1; .//Backtracking
}
else Dfs (x,y+1,cnt,1,1);
}
if (turn==2) {
if (map[x+1][y]==1)
{
map[x+1][y]=0;
DFS (x,y,cnt,2,0);
Map[x+1][y]=1;
}
else Dfs (x+1,y,cnt,2,1);
}
if (turn==3) {
if (map[x][y-1]==1)
{
map[x][y-1]=0;
DFS (x,y,cnt,3,0);
Map[x][y-1]=1;
}
else Dfs (x,y-1,cnt,3,1);
}
if (turn==4) {
if (map[x-1][y]==1)
{
map[x-1][y]=0;
DFS (x,y,cnt,4,0);
Map[x-1][y]=1;
}
else Dfs (x-1,y,cnt,4,1);
}
}
if (flag&&speed) return; This determines the state after the cross-border, because after the cross-border back to the previous position, this time to judge the state of the ball, if it is still, continue to search. If it is moving, continue to return (because the ball does not stop itself when it is moving on a line)
else if (flag&&speed==0) flag=0;
}
int main ()
{
int i,j,k;
while (scanf ("%d%d", &w,&h)!=eof)
{
if (w==0&&h==0) break;
memset (map,0,sizeof (map)); Note that you want to initialize the maze
flag=0;
mini=99999999;
for (i=1;i<=h;i++)
for (j=1;j<=w;j++)
{
scanf ("%d", &map[i][j]);
if (map[i][j]==2) {
Si=i;sj=j;
}
if (map[i][j]==3) {
Ei=i;ej=j;
}
}
DFS (si,sj,0,1,0);
if (mini<99999999)
printf ("%d\n", mini);
else printf (" -1\n");
}
return 0;
}
poj3009 Curling 2.0 (Dfs backtracking)