题目浏览
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
勇士们不小心进入了敌人的地雷阵(用n行n列的矩阵表示,’*‘表示某个位置埋有地雷,’-'表示某个位置是安全的),他们各自需要在规定的步数(一步代表走到和当前位置相邻的位置)内绕开地雷到达出口(第一行第一格,即坐标为(0,0)的位置)才能完成任务,告诉你每个勇士的位置(x,y)和规定的步数s,请你判断每个勇士能否顺利完成任务(1代表“能”,-1代表“不能”)。
输入格式
输入数据的第一行为一个整数n;第二行至第n+1行是n行n列地雷阵的矩阵表示(见输入样例);第n+2行至最后一行每行是一个勇士的位置x、y和到达出口规定的最大步数s,三个整数间用空格隔开。
输出格式
按顺序输出对每个勇士是否能顺利完成任务的判断(1代表“能”,-1代表“不能”),对每个勇士的判断占一行。
样例输入
5
-----
--*--
-**--
-**--
*-*--
0 1 1
0 4 3
1 1 3
1 4 2
2 0 3
3 0 4
3 3 2
4 1 3
样例输出
1
-1
1
-1
1
1
-1
-1
数据规模和约定
1≤n≤500,0≤x≤n-1,0≤y≤n-1,1≤s≤500
算法浏览
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
int n;
char g[N][N];
int dist[N][N];
void bfs(int a, int b)//求a,b点到其他能到的点的距离
{
queue<PII> store;
store.push({a, b});
dist[a][b] = 0;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
while(store.size())
{
pair<int, int> temp = store.front();
store.pop();
for(int i = 0; i < 4; i++){
int nx = temp.x + dx[i], ny = temp.y + dy[i];
if(nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1) continue;
if(dist[nx][ny] != 0) continue;
if(g[nx][ny] == '*') continue;
dist[nx][ny] = dist[temp.x][temp.y] + 1;
store.push({nx, ny});
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++) scanf("%s", &g[i]);
bfs(0,0);
int x,y,z;
while(cin >> x >> y >> z){
if(x == 0 && y == 0) cout << 1 << endl;
else
if(dist[x][y] != 0 && dist[x][y] <= z) cout << 1 << endl;
else cout << -1 << endl;
}
}
核心思路
由于所有点的终点始终为 (0, 0),所以,可以在终点用宽度搜索算法,求出终点到每个点的距离.
之后再读取点的数据,根据 当前的点到终点的距离 与 能动的步数 来比较即可知道答案