#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
const int w=50,h=30;
bool n[w][h];
struct DisNode
{
int dis=w*h*2;
int beforeW=-1;
int beforeH=-1;
char fromWith;//通过什么操作转移过来的。
};
DisNode dis[w][h];
void mapIn()
{
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
char cget=cin.get();
while(cget!='0'&&cget!='1')
{
cget=cin.get();
}
n[j][i]=(cget=='1');
}
}
}
vector<char> getPath(DisNode p)
{
vector<char> v;
int w=p.beforeW;
int h=p.beforeH;
while(w!=-1&&h!=-1)
{
v.push_back(p.fromWith);
p=dis[w][h];
w=p.beforeW;
h=p.beforeH;
}
reverse(v.begin(),v.end());
return v;
}
bool normalData(int w,int h)
{
if(w<0||h<0) return false;
return true;
}
bool aBiggerThanB(DisNode a,DisNode b)//a>=b
{
if(a.dis>b.dis) return true;
else if(a.dis==b.dis)
{
vector<char> pathA=getPath(a);
vector<char> pathB=getPath(b);
for(int i=0;i<pathA.size();i++)
{
if(pathA[i]<pathB[i]) return false;
else if(pathA[i]>pathB[i]) return true;
else if(pathA[i]==pathB[i]) continue;
}
return true;//如果一样大,也算是a>=b
}
else
{
return false;
}
}
bool canMoveToNewState(int nowW ,int nowH,DisNode a,DisNode b,char action)//a 是old状态,b是要转移的状态(现态),其他参数是状态转移信息.
{
b.dis=b.dis+1;
b.beforeH=nowH;
b.beforeW=nowW;
b.fromWith=action;
if(aBiggerThanB(a,b))//如果转移后的状态满足转移条件
{
return true;
}
else
{
return false;
}
}
bool tryMoveToNewState(int nowW,int nowH,int toW, int toH,char action)
{
if(!normalData(toW,toH)) return false;
if(toW<0||toH<0) return false;
if(toW>w-1||toH>h-1) return false;
if(n[toW][toH]) return false; //目标位置是个墙壁无法转移
if(canMoveToNewState(nowW,nowH,dis[toW][toH],dis[nowW][nowH],action))
{
dis[toW][toH].dis=dis[nowW][nowH].dis+1;
dis[toW][toH].beforeH=nowH;
dis[toW][toH].beforeW=nowW;
dis[toW][toH].fromWith=action;
return true;
}
else
{
return false;
}
}
void PrintOut()
{
vector<char> c;
DisNode d= dis[w-1][h-1];
while(d.beforeH!=-1&&d.beforeW!=-1)
{
c.push_back(d.fromWith);
d=dis[d.beforeW][d.beforeH];
}
for(int i=c.size()-1;i>=0;i--)
{
cout<<c[i];
}
}
void DFS(int nowW,int nowH)//入口0,0.出口 49,29
{
//左
if(tryMoveToNewState(nowW,nowH,nowW-1,nowH,'L'))
{
DFS(nowW-1,nowH);
}
//右
if(tryMoveToNewState(nowW,nowH,nowW+1,nowH,'R'))
{
DFS(nowW+1,nowH);
}
//上
if(tryMoveToNewState(nowW,nowH,nowW,nowH-1,'U'))
{
DFS(nowW,nowH-1);
}
//下
if(tryMoveToNewState(nowW,nowH,nowW,nowH+1,'D'))
{
DFS(nowW,nowH+1);
}
}
int main()
{
mapIn();
dis[0][0].dis=0;
DFS(0,0);
PrintOut();
return 0;
}
蓝桥杯·寒假百校真题大联赛(大学B组)(第2期)《迷宫》(DFS版本)
于 2022-02-14 17:21:52 首次发布