算法之BFS广度搜索
题目以及文章采用南阳理工学院举办新生创新大赛题。
代码有待优化,体现出BFS思想,但时间复杂度较高。
会超时。
且经过ACM集训队学长大佬的指导找出一个错误------>搜索的时间要注意范围,寻找的范围要0<=x<n,0<=y<m,否则在BFS期间就会出现搜索到地图以外的位置,从而超时或死循环…但交题还存在超时问题,emmmm…
题目如下:
Input file: standard input
Output file: standard output
Time limit: 1 second
Memory limit: 128 megabytes
早队喜欢和小学妹一起旅游。由于资金有限,只能去峡谷 (一个二维数组) 旅游,但是他可以传送到峡谷的任意一个位置,现在他想知道针对任意的传送位置 (x, y),可以和小学妹一起走多少步?重复走过的地方只算一次。峡谷被定义为二维数组。峡谷只会出现 . 代表路;# 代表怪男爵,碰到就死亡, 在峡谷中只能向上下左右四个方向走。
Input:
第一行两个整数 N, M(1 ≤ N ≤ 1000, 1 ≤ M ≤ 1000),接下来 N 行 M 列迷宫,然后一个 Q(1 ≤ Q ≤ 105) 代表有 Q 次询问,接下来 Q 行,每行包含两个正整数 x, y,表示早队初始被传送到的起点
Output:
输出包含 Q 行,每行输出一个整数代表早队最多可以和小学妹一起旅行多少步,如果一步都无法前
进,请输出 -1.
#include<bits/stdc++.h>
using namespace std;
char a[1005][1005];
int start_x,start_y;
int book[1005][1005];
int n,m;
int time1 = 0;
int point[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
struct position {
int x;
int y;
};
queue<position> r;
void BFS(int c, int d) {
if(a[c][d]=='#') {
} else {
position start,next;
start.x = c;
start.y = d;
r.push(start);
book[start.x][start.y] = 1;
while(!r.empty()) {
int xx = r.front().x;
int yy = r.front().y;
r.pop();
for(int k = 0 ; k < 4 ; k++) {
int px,py;
px = xx + point[k][0];
py = yy + point[k][1];
if(px>=0 && px<n && py>=0 && py<m && book[px][py] == 0 && a[px][py] == '.') {
next.x = px;
next.y = py;
time1++;
r.push(next);
book[px][py] = 1;
}
}
}
}
}
int main() {
scanf("%d %d",&n,&m);
a[n+1][m+1];
for(int i = 0 ; i < n ; i++) {
scanf("%s",a[i]);
}
long long int tt;
scanf("%lld",&tt);
while(tt--) {
memset(book,0,sizeof(book));
scanf("%d %d",&start_x,&start_y);
time1 = 0;
BFS(start_x-1,start_y-1);
if(time1==0) {
printf("-1\n");
} else {
printf("%d\n",time1);
}
}
}