汤圆の拯救计划
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
又到了汤圆星球一年一度的汤圆节了,但是大魔王却过来把汤圆公主抓走了Σ( ° △ °|||)︴
身为汤圆骑士的QAQ蒟蒻自然而然的肩负着拯救汤圆的使命
QAQ蒟蒻经历了千辛万苦(并没有)之后,来到了大魔王的城堡,根据情报,汤圆公主就被大魔王放在城堡内,然后QAQ蒟蒻发现自己是一个路
痴,所幸的是他拿到了大魔王的城堡的地图,而且在这上面标注了自己和汤圆公主的位置,那么问题来了,聪明的你能帮他计算出需要多少单位
的时间来赶到汤圆公主的位置吗?
Ps:QAQ蒟蒻每一次都可以移动到相邻的非墙的格子中,每次移动都要花费1个单位的时间
有公共边的格子定义为相邻
Input
一开始为一个整数T代表一共有T组数据
每组测试数据的第一行有两个整数n,m (2<=n,m<=300)
接下来的n行m列为大魔王的迷宫,其中
’#’为墙壁,‘_‘为地面
A代表QAQ蒟蒻,O代表汤圆公主:
Output
一组数据输出一个整数代表从QAQ蒟蒻到汤圆的位置的最短时间
如果QAQ蒟蒻不能到达汤圆的位置,输出-1
Example Input
2
3 3
__A
_##
__O
2 2
A#
/#O
Example Output
6
-1
Hint
Author
QAsQ
比赛时写的代码如下
#include <iostream>
#include <queue>
#include <string.h>
#include <stdio.h>
using namespace std;
int rows,column;
char map[350][350];
bool visit[350][350];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x,y;
int step;
}s;
bool judge(int x,int y)
{
if(x>=1&&x<=column&&y>=1&&y<=rows&&map[y][x]!='#'&&visit[y][x]==0)
return true;
return false;
}
int bfs()
{
queue<node> q;
q.push(s);
memset(visit,false,sizeof(visit));
while(!q.empty())
{
node f = q.front();
q.pop();
if(map[f.y][f.x]=='O')
{
return f.step;
}
for(int i = 0;i<4;i++)
{
node next = f;
next.x += dir[i][0];
next.y += dir[i][1];
if(judge(next.x,next.y))
{
next.step++;
visit[next.y][next.x] = true;
q.push(next);
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>rows>>column;
getchar();
for(int i= 1;i<=rows;i++)
{
for(int j = 1;j<=column;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='A')
{
s = (node) {j,i,0};
}
}
getchar();
}
visit[s.y][s.x] = true;
s.step = 0;
cout<<bfs()<<endl;
}
return 0;
}
/***************************************************
User name: rj160206武志祥
Result: Wrong Answer
Take time: 0ms
Take Memory: 388KB
Submit time: 2017-07-24 19:25:47
****************************************************/
在网上看到各位大佬的代码后发现在读取地图的数据时都和我的不一样,于是修改如下:
#include <iostream>
#include <queue>
#include <string.h>
#include <stdio.h>
using namespace std;
int rows,column;
char map[350][350];
bool visit[350][350];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x,y;
int step;
}s;
bool judge(int x,int y)
{
if(x>=1&&x<=column&&y>=1&&y<=rows&&map[y][x]!='#'&&visit[y][x]==0)
return true;
return false;
}
int bfs()
{
queue<node> q;
q.push(s);
memset(visit,false,sizeof(visit));
while(!q.empty())
{
node f = q.front();
q.pop();
if(map[f.y][f.x]=='O')
{
return f.step;
}
for(int i = 0;i<4;i++)
{
node next = f;
next.x += dir[i][0];
next.y += dir[i][1];
if(judge(next.x,next.y))
{
next.step++;
visit[next.y][next.x] = true;
q.push(next);
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>rows>>column;
for(int i = 0;i<rows;i++)
{
scanf("%s",*(map+i+1)+1);
}
for(int i= 1;i<=rows;i++)
{
for(int j = 1;j<=column;j++)
{
if(map[i][j]=='A')
{
s = (node) {j,i,0};
}
}
}
visit[s.y][s.x] = true;
s.step = 0;
cout<<bfs()<<endl;
}
return 0;
}
然后就莫名ac了,还望看到的大佬多多指点。