这道题的题意是:让你找出最短路,并且最短路的方式有多少种。
大致思路为,先正向搜索,再反向搜索。
具体情况看题解
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
#define maxn 105
int n,m,k,i,x,y;
struct node
{
int x,y;
} s,e;
int a[maxn][maxn],total;
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
void bsf(node num)
{
int i;
queue<node> q;
a[num.x][num.y]=1;//避免搜索时被重新再搜到。。。
node fr,nex;
q.push(num);
while(!q.empty())
{
fr=q.front(),q.pop();
for(i=0; i<4; i++)
{
nex.x=fr.x+dir[i][0];
nex.y=fr.y+dir[i][1];
if(a[nex.x][nex.y]==0&&nex.x>=1&&nex.x<=n&&nex.y>=1&&nex.y<=m)
{
q.push(nex);
a[nex.x][nex.y]=a[fr.x][fr.y]+1;
}
}
}
}
void search(int x,int y)//判断在最短时间内能回到开始点的路径有多少条
{
int i;
if(x==s.x&&y==s.y)
{
total++;
return;
}
else
{
for(i=0; i<4; i++)
{
if(a[x+dir[i][0]][y+dir[i][1]]==a[x][y]-1)
search(x+dir[i][0], y+dir[i][1]);
}
}
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&k))
{
total=0;
memset(a,0,sizeof(a));
for(int i=0; i<k; i++)
{
scanf("%d %d",&x,&y);
a[x][y]=-1;
}
scanf("%d%d%d%d",&s.x,&s.y,&e.x,&e.y);//s.x,s.y代表开始地点,e.x,e.y代表结束地点
node num;
num.x=s.x;
num.y=s.y;
bsf(num);
if(a[e.x][e.y]==0)//如果最后没有能到终点的路
printf("No Solution!/n");
else
{
search(e.x,e.y);//反向搜索,查找最短路径
printf("%d\n%d\n",a[e.x][e.y]-1,total);//减一是因为开始时初始化已经走了一步
}
}
return 0;
}