7-41 最近距离
在一个游戏中,玩家处于一个如下所示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
其中迷宫由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。
#include <bits/stdc++.h>
using namespace std;
int map1[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 a,b,c,d,mint=10000;
int countt;
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
void f(int m,int n){
if(c==m&&d==n){
if(countt<mint){
mint=countt;
}
}
for(int i=0;i<4;i++){
if(m+dx[i]>=0&&m+dx[i]<12&&n+dy[i]<12&&n+dy[i]>=0 && !map1[m+dx[i]][n+dy[i]]&&countt<mint){//这里使用了剪枝
map1[m+dx[i]][n+dy[i]]=1;
countt++;
f(m+dx[i],n+dy[i]);
map1[m+dx[i]][n+dy[i]]=0;//记得回溯
countt--;
}
}
}
int main(){
cin>>a>>b>>c>>d;
f(a,b);
cout<<mint;
return 0;
}