题目描述
夏天的时候,ThinkSpirit 实验室去海边玩了。蒙起眼睛的 Crush 举起了木棒,他要在大家的帮助下打西瓜。
沙滩可以被描述成一个 N × M 的网格,其中某些格子为不可移动的障碍物。Crush 总是在格子上,始终在格子上移动,且不会走出边界。西瓜也处于一个格子上,当 Crush 走到西瓜所在格子,他就会举起木棒,重重挥下 —— 啪!
好心的其它成员当然会说出提示,来帮助 Crush ,每个提示都会让 Crush 走向相邻的一个可走的格子。问最少需要多少条提示,才能让 Crush 打到西瓜?
输入描述
第一行两个正整数 N , M ( N , M ⩽ 50 ),表示沙滩的大小。
接下来 N 行,每行 M 个用空格隔开的 0 或 1,表示沙滩的构造。其中,0 表示此格点无障碍,1 表示此格点为不可移动的障碍物。
最后一行输入 4 个整数,分别表示 Crush (起始点)和西瓜(目标点)所在网格的行号与列号。(行号和列号从 1 开始,行号从上往下递增,列号从左往右递增)
输出描述
一个整数,表示需要的最小提示数,如果无论接收多少提示 Crush 都不能抵达西瓜,输出 -1。
样例输入
9 10
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 1 0
3 3 4 4
样例输出
6
题目思路:
这是一道BFS模板题,可以自己定义数据结构
代码1:
#include<bits/stdc++.h>
using namespace std;
struct node
{
int x,y;
int step;
} S,T,Node;
int n,m;
int tmp;
const int maxn = 55;
int maze[maxn][maxn];
bool inq[maxn][maxn]={false};
int X[4]={-1,0,0,1};
int Y[4]={0,-1,1,0};
bool test(int x,int y) {
if(x>n || x<=0 || y>m || y<=0) return false;
if(maze[x][y]==1) return false;
if(inq[x][y]==true) return false;
return true;
}
int BFS() {
queue<node> q;
q.push(S);
while(!q.empty()) {
node top = q.front();
q.pop();
if(top.x == T.x && top.y == T.y) {
return top.step;
}
for(int i=0; i<4; i++) {
int newX = top.x+X[i];
int newY = top.y+Y[i];
if(test(newX,newY)) {
Node.x = newX;
Node.y = newY;
Node.step = top.step +1;
q.push(Node);
inq[newX][newY] = true;
}
}
}
return -1;
}
int main() {
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
scanf("%d",&tmp);
if(tmp == 0) {
maze[i][j] = 0;
} else {
maze[i][j] = 1;
}
}
}
scanf("%d%d",&S.x,&S.y);
scanf("%d%d",&T.x,&T.y);
S.step = 0;
printf("%d\n",BFS());
return 0;
}
代码2:
#include<bits/stdc++.h>
#include<iostream>
#include<queue>
using namespace std;
typedef pair<int,int> P;
int n,m;
int sx,sy,gx,gy;//起点和终点的坐标
int tmp;
const int INF = 100000000;
const int maxn=55;
char maze[maxn][maxn];
int d[maxn][maxn];
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
bool test(int x,int y) {
if(x>n || x<=0 || y>m || y<=0) return false;
if(maze[x][y]=='1') return false;
if(d[x][y]!=INF) return false;
return true;
}
int bfs() {
queue<P> q;
for (int i = 1; i <= n; i++)
{
/* code */
for (int j = 1; j <= m; j++)
{
/* code */
d[i][j]=INF;
}
}
q.push(P(sx,sy));
d[sx][sy]=0;
while(!q.empty()) {
P p=q.front();
q.pop();
if(p.first == gx && p.second == gy) {
break;
}
for(int i=0; i<4; i++) {
int nx = p.first+dx[i];
int ny = p.second+dy[i];
if(test(nx,ny)) {
q.push(P(nx,ny));
d[nx][ny] = d[p.first][p.second]+1;
}
}
}
return d[gx][gy];
}
int main() {
cin>>n>>m;
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
cin>>maze[i][j];
}
}
}
cin>>sx>>sy>>gx>>gy;
cout<<bfs()<<endl;
return 0;
}