POJ3009DFS

DFS的简单应用。

#include<iostream>

using namespace std;
const int N=25;
int movex[4]={0,0,-1,1};
int movey[4]={-1,1,0,0};
int maze[N][N];
int nx,ny;
struct node
{
int x,y;
node(int _x=0,int _y=0){x=_x;y=_y;}
};
node start;
node getnext(node now,int dire)
{
int x=now.x;
int y=now.y;
if(maze[y+movey[dire]][x+movex[dire]]==1)
return node(0,0);
while(x+=movex[dire],y+=movey[dire],x>=1&&x<=nx&&y>=1&&y<=ny)//先前把x+=movex[dire],y+=movey[dire]写在while语句里面就一直wa,因为在main里每次循环没有加//memset(maze,0,sizeof(maze));
{
if(maze[y][x]==3)
return node(N-1,N-1);
if(maze[y][x]==1)
return node(x-movex[dire],y-movey[dire]);
}
return node(0,0);
}
int ans=11;
void dfs(int x,int y,int step)
{
if(step>10)
return ;
for(int i=0;i<4;i++)
{
node next=getnext(node(x,y),i);
if(next.x==0)
continue;
if(next.x==N-1)
{
ans=ans<step?ans:step;
return;
}
maze[next.y+movey[i]][next.x+movex[i]]=0;
dfs(next.x,next.y,step+1);
maze[next.y+movey[i]][next.x+movex[i]]=1;
}
}
int main()
{
//freopen("C:\\Users\\wuyanyisb\\Desktop\\1.txt","r",stdin);
while(scanf("%d%d",&nx,&ny),ny!=0||nx!=0)
{
//memset(maze,0,sizeof(maze));
for(int i=1;i<=ny;i++)
for(int j=1;j<=nx;j++)
{
scanf("%d",&maze[i][j]);
if(maze[i][j]==2)
{
start.x=j;
start.y=i;
}
}
ans=11;
dfs(start.x,start.y,1);
if(ans==11)
printf("-1\n");
else
printf("%d\n",ans);
}
system("pause");
return 0;
}

你可能感兴趣的:(c,System)