Pergunta

I am doing this problem http://community.topcoder.com/stat?c=problem_statement&pm=2915&rd=5853, but my program gives wrong output, I tried more ways and it does not work properly. I do not get it, because other people do it like me and they are fine. Can you please check if I have properly implemented the BFS? Thanks in advance.

#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;
    } 
};
Foi útil?

Solução

I think the problem might be that you push y,x,d so your queue will be

Front y  Middle x End d

But when you pop the front element you place it (y) into a variable called d.

It may work better if you change:

    int d = s.T s.PP
    int x = s.T s.PP
    int y = s.T s.PP

to

    int y = s.T s.PP
    int x = s.T s.PP
    int d = s.T s.PP
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top