Life has its own fate, and meeting may not be accidental.

0%

Pta-7-50 最近距离 (25分)(DFS)

题目

在一个游戏中,玩家处于一个如下所示12行12列的迷宫:

1
2
3
4
5
6
7
8
9
10
11
12
0,1,0,0,0,1,1,1,0,1,0,1
0,0,0,1,0,0,0,0,1,0,0,1
0,1,0,1,0,1,1,1,0,1,0,0
0,1,0,0,0,0,0,1,0,0,1,1
0,0,0,0,1,0,0,0,0,0,0,0
0,0,1,0,0,0,1,0,0,0,1,0
0,0,1,0,0,0,0,0,1,0,0,0
1,0,0,1,0,1,0,0,0,1,0,1
0,0,1,0,1,0,1,0,1,0,0,0
0,0,0,0,0,1,0,0,0,1,1,0
0,0,0,0,0,1,0,0,0,0,0,0
0,1,0,1,0,0,0,1,0,1,0,0

其中迷宫由0,1组成,0表示道路,1表示障碍物。
现在要根据玩家和游戏中被攻击的虚拟boss所在位置,给玩家以最近距离的提示。
最近距离:即玩家走到boss所走的最少步数。(注:路线中的一步是指从一个坐标点走到其上下左右相邻坐标点。)

输入格式:

输入4个整数a,b,c,d(即玩家和虚拟boss在迷宫中的坐标位置分别为(a,b) 、(c,d)), 其中 0<=a,b,c,d<12。

输出格式:

输出在迷宫中从(a,b)出发到达(c,d)的最少步数,如果(a,b)永远无法到达(c,d)则输出10000。

输入样例:

1
0 0 11 11

输出样例

1
22

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
using namespace std;
int a,b,c,d,flag=0,Min;
int Map[12][12]={0,1,0,0,0,1,1,1,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0};
int vis[20][20];
int dir[4][2]={0,1,0,-1,-1,0,1,0};
int stepA[100][2];//记录当前路径
int stepB[100][2];//记录最短路径
void dfs(int x,int y,int step){
if(step>Min){
return;
}
if(x==c&&y==d){
Min=step;
return;
}
for(int i=0;i<4;i++){
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx<0||yy<0||xx>=12||yy>=12){
continue;
}
if(!vis[xx][yy]&&Map[xx][yy]==0){
vis[xx][yy]=1;
dfs(xx,yy,step+1);
vis[xx][yy]=0;
}
}
return;
}
int main(){
scanf("%d %d %d %d",&a,&b,&c,&d);
memset(vis,0,sizeof(vis));
vis[a][b]=1;
Min=10000;
dfs(a,b,0);
if(Min==10000){
printf("10000\n");
}
else{
printf("%d\n",Min);
}
return 0;
}