3166: 共享单车
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 45 Solved: 19
[ Submit][ Status][ Web Board]
Description
共享单车走进烟台,小明决定尝试。小明启动共享单车app,轻松地找到附近的单车。那么问题来了,到最近的那辆单车,小明大约要走多少米呢?
现在简化问题。将地图设定成一个由100米*100米的像素块组成的二维平面区域。如果一个方块内有单车,则像素块显示为字符“x”;如果此方块内是可以通行的路,则显示为“.”;再如果方块是建筑物,则显示为“*”,建筑物不能通行。
小明在地图上的位置显示为“o”,可以朝,“上”、“下”、“左”,“右”,“左上”,“左下”,“右上”,“右下”八个方向走。下图所示为一个小明站在像素方块O,如果小明向右走到X,则走100米;如果向右上走,则走141米(不需要开方)。
假设小明和单车都在方块的中央。现在给出 T 幅根据以上规则建立的地图,地图行数和列数分别为 n 和 m,请分别估算小明要走多少米才能到最近的单车?
如果计算中出现小数,那么直接舍弃。最后的输出的结果为整型。
给出的地图中至少有一辆单车,如果最终无法到达单车的位置,输出-1。
Input
第1行,T,表示下面有 T 组测试数据
对于每组测试数据
(1)第1行,n和m ,表示地图的大小;
(2)第2行开始,给出具体的地图 。
Output
T行数据
每行1个整数,表示问题的解
Sample Input
2
3 8
.....x..
.o...x..
........
8 10
.***......
.***......
.***..x...
..........
.....*****
..o..*****
.......x..
...*******
Sample Output
400
523
解题新知:可看做另一种 bfs模板
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char mmap[105][105];
int dir[8][2] = {{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};
typedef struct Node
{
int x;
int y;
int step;
}node;
int ans;
node start,now,next;
queue<node>q;
void check()
{
if(mmap[next.x][next.y] == '.')
{
q.push(next);
mmap[next.x][next.y] = '*';
}
if(mmap[next.x][next.y] == 'x')
{
q.push(next);
}
}
void bfs()
{
q.push(start);
while(!q.empty())
{
now = q.front();
if(mmap[now.x][now.y] == 'x')
{
ans = now.step;
return;
}
for(int i = 0;i<8;i++)
{
next.x = now.x+dir[i][0];
next.y = now.y+dir[i][1];
if(dir[i][0] && dir[i][1])
next.step = now.step+141;
else
next.step = now.step+100;
check();
}
q.pop();
}
ans = -1;
}
int main()
{
int t;
scanf("%d",&t);
int n,m;
while(t--)
{
memset(mmap,0,sizeof(0));
while(!q.empty())
{
q.pop();
}
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mmap[i][j];
if(mmap[i][j] == 'o')
{
start.x = i;
start.y = j;
start.step = 0;
}
}
}
bfs();
printf("%d\n",ans);
}
return 0;
}
/**************************************************************
Problem: 3166
Language: C++
Result: Accepted
Time:0 ms