错误的最短距离BFS算法
Wrong shortest distance BFS algorithm?
我正在做这个问题http://community.topcoder.com/stat?c=problem_statement&pm=2915&rd=5853,但是我的程序给出了错误的输出,我尝试了更多的方法,它不能正常工作。我不明白,因为其他人和我一样这么做,而且他们很好。请检查我是否正确执行了BFS?提前谢谢。
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
#define P push
#define PP pop();
#define T front();
int mo[][2] = { {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {1, -2}, {-1, 2}, {1, 2} };
int m[8][8];
int BFS(int sy, int sx, int fy, int fx)
{
queue<int> s;
m[sy][sx] = 1;
s.P(sy);
s.P(sx);
s.P(0);
while(!s.empty())
{
int d = s.T s.PP
int x = s.T s.PP
int y = s.T s.PP
for(int i=0;i < 8;i++)
{
int yy = y + mo[i][0];
int xx = x + mo[i][1];
if(yy < 0 || yy > 7 || xx < 0 || xx > 7) continue;
if(m[yy][xx] != -1) continue;
if(yy == fy && xx == fx) return d + 1;
m[yy][xx] = 0;
s.P(yy);
s.P(xx);
s.P(d+1);
}
}
return -1;
}
class CaptureThemAll {
public:
int fastKnight(string knight, string rook, string queen) {
vector<int> p{knight[0] - 'a', knight[1] - '1', rook[0] - 'a', rook[1] - '1', queen[0] - 'a', queen[1] - '1'};
memset(m, -1, sizeof(m));
int a = BFS(p[1], p[0], p[3], p[2]);
memset(m, -1, sizeof(m));
int b = BFS(p[1], p[0], p[5], p[4]);
memset(m, -1, sizeof(m));
int c = BFS(p[3], p[2], p[5], p[4]);
return min(a,b) + c;
}
};
我认为问题可能是你按了y,x,d所以你的队列将是
Front y Middle x End d
但是当你弹出前面的元素时,你把它(y)放入一个名为d的变量中。
如果您更改:
int d = s.T s.PP
int x = s.T s.PP
int y = s.T s.PP
int y = s.T s.PP
int x = s.T s.PP
int d = s.T s.PP
相关文章:
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 这条代码线在双方图算法中通过BFS做什么
- 为什么BFS算法并不总是能找到魔方的解?
- C++:basic_string::_M_construct 空,对于图形 BFS 算法无效错误
- 如何在BFS算法中计算移动?(迷宫中的最短路径)
- 用BFS算法求两节点间的最短路径
- 什么是适用于多个入口和多个出口的类似BFS的最佳路径算法
- BFS的伪代码(来自算法设计,第二版)混淆
- 如何用BFS算法表示生成树的预序
- 使用BFS算法寻找最短路径
- 调试使用广度优先搜索(BFS)的简单图算法
- 如何使用BFS算法只保留外部点
- 错误的最短距离BFS算法