农夫抓羊,有三种路径,求最短路。
虽然是很简单的bfs,但是却 10次 才A过。
这道题有以下要注意的:
1.如果你 内存超限了(Memory Limit Exceeded),那么,那些曾经走过的点做个标记,不再加入队列(容易证明曾经走过的再走,一定不是最短路)
2.如果你 WA 了,当 起点 与终点相同时,step是0
AC代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define maxn 100005
int n, m;
int s[] = { 1, -1, 0 };
int mr[maxn];
struct node{
int index, step;
};
int bfs(){
if (m == n){
return 0;
}
queue<node> q;
node x, y;
int i;
x.index = n;
x.step = 0;
q.push(x);
while (!q.empty()){
x = q.front();
q.pop();
s[2] = x.index;
for (i = 0; i < 3; i++){
y.index = x.index + s[i];
y.step = x.step + 1;
if (y.index == m){
return y.step;
}
if (y.index <= 100000 && y.index >= 0 && mr[y.index] == 0){
mr[y.index] = 1;
q.push(y);
}
}
}
return -1;
}
int main(){
int num;
while (cin >> n >> m){
memset(mr, 0, sizeof(mr));
num = bfs();
cout << num << endl;
}
return 0;
}