题目详情:
小明同学来到西安工业大学后,听说了计算机学院有红细胞和网安两个协会,但是它们的招新比赛时间冲突了,小明同学只能选择一个去参加。小明同学开始的位置在图书馆(图中左上角且固定不变),由于小明同学不想多走路,所以他决定去距离自己最近的比赛地点。题目保证最短路径距离唯一且距离最近的协会一定存在通路。
图书馆:字母’L’表示 红细胞: 字母’R’表示 网安:字母’S’表示 障碍物:字母’X’表示 可以走的路:字母’O’表示
其中‘L’,‘R’,‘S’,‘O’均为可以走的路。图示红色为一条长度为7的最短路。
输入格式: 10行,每行包含10个字符。输出格式: 输出为一行,先输出距离自己最近的协会,再输出小明到达该点的最短路径长度(走1步算1个单位长度)。
输入样例:
LXXXXXXXXX
OOOXXXXXXX
OXOOXXOOOX
XXOXXXXXXX
XXOOXXXXXX
XXRXXXXXXX
XXOOXOOOOO
XXXOXOOOOO
XXOOXXXXXX
XOOOOOOOOS
输出样例:
R 7
分析:从最短路(最优解)中,我们可以很容易想到用BFS,因为BFS是一层一层展开的,最先到达的肯定是最短的。然后我们就可以跑裸的BFS就行了(用一个结构体存点和到这个点的步数信息)。
AC代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<set>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e5+5;
string s[15];
//控制上下左右
int x[4]={-1,1,0,0};
int y[4]={0,0,-1,1};
int vis[12][12];//记录点是否访问
struct node{
int xx,yy,num;
//一个构造函数
node(int xx,int yy,int num):xx(xx),yy(yy),num(num){
}
};
void bfs(){
queue<node>q;
q.push(node(0,0,0));
vis[0][0]=1;//标记已经访问过的,防止重复走
while(q.size()){
node t=q.front();q.pop();
char ch=s[t.xx][t.yy];
if(ch=='R'||ch=='S'){
cout<<ch<<" "<<t.num;//直接输出返回
return ;
}
for(int i=0;i<4;i++){
int tx=t.xx+x[i],ty=t.yy+y[i];
if(tx>=10||ty>=10||tx<0||ty<0)
continue;
if(s[tx][ty]!='X'&&!vis[tx][ty])
q.push(node(tx,ty,t.num+1)),vis[tx][ty]=1;
}
}
}
int main(){
for(int i=0;i<10;i++)
cin>>s[i];
bfs();
return 0;
}