迷宫问题
给定一个m × n(m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到另外一个位置,当然迷宫中有些地方是空地,gloria可以穿越,有些地方是障碍,她必须绕行,从迷宫的一个位置,只能走到与它相邻的4个位置中,当然在行走过程中,gloria不能走到迷宫外面去。令人头痛的是,gloria是个没什么方向感的人,因此,她在行走过程中,不能转太多弯了,否则她会晕倒的。我们假定给定的两个位置都是空地,初始时,gloria所面向的方向未定,她可以选择4个方向的任何一个出发,而不算成一次转弯。gloria能从一个位置走到另外一个位置吗?
样例输入
5 5
...**
*.**.
.....
.....
*....
1 1 1 1 3
5 5
...**
*.**.
.....
.....
*....
2 1 1 1 3
样例输出
no
yes
解:
迷宫问题:从出发位置开始,到达目的坐标结束,如果拐弯次数在给定范围则可行
假定每个位置都有上下左右四种方向可走,
要求拐弯的次数即当前方向与上一次方向不同为拐弯一次,所以假定初始状态的方向为(0,0);
由于出发的第一步不计入拐弯次数所以最后的结果要减 1 ;
每次都有四种方向可走,如果当前方向可走,则进行下一位置的判断
不可走,则进行下一方向的判断
#include<stdio.h>
int m,n;
int x1,y1,x2,y2;
int flag=0;//标记能否到达
int maxcount;//最大上限
int count=0;//拐弯次数
int dirction=0;//当前方向
int offset[5][2]={0,0,0,1,0,-1,1,0,-1,0};//方向数组
char map[100][100];//迷宫矩阵
bool ok(int x,int y)
{//判断是否超出边界并且不能是 '*'
if(x<0 || y<0 || x>=m || y>=n || map[x][y]=='*')
return false;
return true;
}
void dfs(int x,int y)
{
//如果当前拐弯次数大于上限
if(count>maxcount+1)
return;
if(flag)//如果之前找到一条路径能满足不需要继续找
return;
if(x==x2 && y==y2)
{//到达目的位置
if(count<=maxcount+1)
flag=1;
return;
}
//每个位置都有4个方向
for(int i=1;i<5;i++)
{
int newx=x+offset[i][0];
int newy=y+offset[i][1];
int olddirction = dirction;
if(ok(newx,newy))
{//如果当前位置可以走
if(dirction!=i)//当前方向与上一方向不同
count++;
dirction=i;
dfs(newx,newy);
if(olddirction!=i)
count--;
dirction=olddirction;
}
}
}
int main()
{
int i,j;
int T;
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
scanf("%s",&map[i]);
}
scanf("%d %d %d %d %d",&maxcount,&x1,&y1,&y2,&x2);
x1=x1-1;y1=y1-1;x2=x2-1;y2=y2-1;
dfs(x1,y1);
if(flag)
printf("yes\n");
else
printf("no\n");
return 0;
}